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
help('nonlocal') The
nonlocal
statement
nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
The
nonlocal
statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.Names listed in a
nonlocal
statement, unlike to those listed in aglobal
statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).Names listed in a
nonlocal
statement must not collide with pre- existing bindings in the local scope.See also:
PEP 3104 - Access to Names in Outer Scopes
The specification for thenonlocal
statement.Related help topics: global, NAMESPACES
Source: Python Language Reference