What does the Python nonlocal
statement do (in Python 3.0 and later)?
There's no documentation on the official Python website and help("nonlocal")
does not work, either.
What does the Python nonlocal
statement do (in Python 3.0 and later)?
There's no documentation on the official Python website and help("nonlocal")
does not work, either.
A google search for "python nonlocal" turned up the Proposal, PEP 3104, which fully describes the syntax and reasoning behind the statement. in short, it works in exactly the same way as the
global
statement, except that it is used to refer to variables that are neither global nor local to the function.Here's a brief example of what you can do with this. The counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.
Obviously, you could write this as a generator, like:
But while this is perfectly idiomatic python, it seems that the first version would be a bit more obvious for beginners. Properly using generators, by calling the returned function, is a common point of confusion. The first version explicitly returns a function.
Source: Python Language Reference
@ooboo:
It takes the one "closest" to the point of reference in the source code. This is called "Lexical Scoping" and is standard for >40 years now.
Python's class members are really in a dictionary called
__dict__
and will never be reached by lexical scoping.If you don't specify
nonlocal
but dox = 7
, it will create a new local variable "x". If you do specifynonlocal
, it will find the "closest" "x" and assign to that. If you specifynonlocal
and there is no "x", it will give you an error message.The keyword
global
has always seemed strange to me since it will happily ignore all the other "x" except for the outermost one. Weird.