[Python-Dev] PEP for Better Control of Nested Lexical Scopes

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Feb 21 10:58:55 CET 2006


Josiah Carlson wrote:

> Mechanisms which rely on manipulating variables within closures or
> nested scopes to function properly can be elegant, but I've not yet seen
> one that *really* is.

It seems a bit inconsistent to say on the one hand
that direct assignment to a name in an outer scope
is not sufficiently useful to be worth supporting,
while at the same time providing a way to do it for
one particular scope, i.e. 'global'. Would you
advocate doing away with it?

 > Of course using
> classes directly with a bit of work can offer you everything you want
> from a closure, with all of the explcitness that you could ever want.

There are cases where the overhead (in terms of amount
of code) of defining a class and creating an instance of
it swamps the code which does the actual work, and,
I feel, actually obscures what is being done rather
than clarifies it. These cases benefit from the ability
to refer to names in enclosing scopes, and I believe
they would benefit further from the ability to assign
to such names.

Certainly the feature could be abused, as can the
existing nested scope facilities, or any other language
feature for that matter. Mere potential for abuse is
not sufficient reason to reject a feature, or the
language would have no features at all.

Another consideration is efficiency. CPython currently
implements access to local variables (both in the
current scope and all outer ones except the module
scope) in an extremely efficient way. There's
always the worry that using attribute access in
place of local variable access is greatly increasing
the runtime overhead for no corresponding benefit.

You mention the idea of namespaces. Maybe an answer
is to provide some lightweight way of defining a
temporary, singe-use namespace for use within
nested scopes -- lightweight in terms of both code
volume and runtime overhead. Perhaps something like

   def my_func():
     namespace foo
     foo.x = 42

     def inc_x():
       foo.x += 1

The idea here is that foo wouldn't be an object in
its own right, but just a collection of names that
would be implemented as local variables of my_func.

Greg


More information about the Python-Dev mailing list