[Python-Dev] nonlocals() function? (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Sat Apr 3 15:31:59 CEST 2010


Steve Bonner wrote:

What do we think of adding a built-in nonlocals() function that would be similar to globals() and locals()? Like those functions, it would return a dictionary of variable names and their values. Since we now have the nonlocal statement, it would be consistent to keep the three scopes local/nonlocal/global with parallel capabilities. And it might sometimes be useful for code inside a nested function to see what variables are available at the enclosing level.

That isn't as easy as it may sound. locals() and globals() are each single namespaces, while the nonlocals may actually span multiple namespaces.

Python actually deals with this at compilation time and when the function object is created - the interpreter knows the names of all the nonlocal cells that need to be connected, and creates the appropriate links to the cells in the outer scopes.

That situation doesn't translate well to dict-style access - while the whole local namespace is readily accessible to the interpreter, as is a pointer to the module namespace (for globals()), no such convenient data source exists for the full set of possible nonlocal references from an arbitrary function.

Cheers, Nick.

-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia



More information about the Python-Dev mailing list