[Python-ideas] Tweaking closures and lexical scoping to include the function being defined
ncoghlan at gmail.com
Fri Sep 30 13:07:38 CEST 2011
On Fri, Sep 30, 2011 at 1:25 AM, Ron Adam <ron3200 at gmail.com> wrote:
> In otherwords the nonlocal feature can be moved into the Function class
> constructor. It doesn't need to actually be in the function it self.
It's *really* important to remember the difference between compilation
time, definition time and call time in this discussion, since name
binding affects all of them.
Compilation time (usually at module import):
Compiler decides between STORE_FAST (function local), STORE_DEREF
(function closure/nonlocal), STORE_GLOBAL (global declaration) and
STORE_NAME (class/module scope).
Definition time (i.e. when the def statement itself is executed to
create the function object):
Compiler creates any decorators, any default arguments, loads
references to any outer cells on to the stack, loads the code object
for the function body, creates the function (passing in the default
arguments, cell references and code object), and only then applies the
Call time (i.e. when the function is called):
Initialises the execution frame with space for the local variables
and references to the cells for variables that may persist beyond this
call, binds the arguments to the appropriate locals (potentially
filling some in from the default arguments) and then passes the code
object to the main eval loop to be executed.
The reason nonlocal and global declarations need to exist in the first
place is precisely to override the compiler's default assumption that
all name bindings in function scope are references to local variables.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas