nested_scopes totally broken?

Eyal Lotem eyal at hyperroll.com
Mon Oct 22 18:14:26 EDT 2001


Playing around with nested_scopes from __future__ (in Python 2.1), I have 
encountered very unexpected behaviour.

What I thought, was that nested scopes will implement fully-functional 
closure behaviour, so that local function code seems to transparently run 
in the parent-function context, and within its variable namespaces.

What I encountered, was a cheap copy of the locals() scope :)
I could not change variable bindings (assign to variable references) of the 
external scope, let alone define new variables in it.

There are two things in here that are in conflict:
A) Local functions should retain their locality, with local variables and 
such being local to their use and removed/rid-of with the function's exit.
B) Local functions should have seamless access to the scope of the external 
function.

This means one of three options:
A) Local functions retain their own local scope, which extends the 
locals()/etc scope of the external function, but sits on top of it, and is 
not actually using it (The current way).
B) Local functions are seamlessly part of the external function's scope, 
meaning that they have no locality, and any local variables used for some 
internal calculations/etc override external function variables, and remain 
visible later.
C) Local functions especially specify which variables should be 'mapped' to 
the external scope directly, much like the 'global' statement.

I think C is the only solution that works for the needs of closure users.
Sometimes I'd love to have access to the locals() scope of the external 
function, however, for most of the things, I'd prefer local functions to 
retain their locality.  Therefore, the ideal balance is C, where one has 
both variables in the internal scope, and ones mapped to upper scopes.

If I'm way off, feel free to correct me.
This is all based on my experience and needs from nested scopes.




More information about the Python-list mailing list