[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Sep 26 08:56:02 CEST 2011

Nick Coghlan wrote:

> In current Python, ordinary named references can refer to one of 4 namespaces:
 > ...
> - closure reference (stored in a cell object by the function that
> defined it, kept alive after the frame is recycled by references from
> still living inner functions that need it)
 > ...

I think you're mixing up concepts and implementation here a
bit. Cells are an implementation detail. What's important is
which *namespace* the name is referring to:

- A 'global' declaration makes it refer to the module-level

- A 'nonlocal' declaration makes it refer to some namespace in
   between local and module-level (there may be more than one of
   these, so I wouldn't say that there are only 4 namespaces).

Now, while the *value* of your proposed new kind of variable
would be stored as part of the function's closure, its *name*
would be part of the function's *local* namespace. Consider

     i = 88

     def f():
         nonlocal i = 17
         print i

     def g():
         nonlocal i = 42
         print i

     print i

I'm assuming you intend that the two i's here would have nothing
to do with each other, or with the i in the enclosing scope, so
that the output from this would be


rather than


So, your proposed use of 'nonlocal' would actually be declaring
a name to be *local*. That strikes me as weird and perverse.


More information about the Python-ideas mailing list