What does the Python nonlocal
statement do (in Python 3.0 and later)?
There\'s no documentation on the official Python website and help(\"nonloca
@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 do x = 7
, it will create a new local variable "x".
If you do specify nonlocal
, it will find the "closest" "x" and assign to that.
If you specify nonlocal
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.