nonlocal
- other
- Specialized
- The nonlocal keyword allows you to modify a variable from an enclosing function in Python.
Examples
-
Without nonlocal, the assignment would create a new local variable instead of modifying the outer one.
-
If you want to change a variable defined outside the inner function, use nonlocal.
-
The variable is defined as nonlocal.
-
You must declare the variable as nonlocal to modify it.
-
The nonlocal keyword is required when you want to alter a variable from an outer function within a nested definition in Python.
-
To access a variable from the nearest enclosing scope, you can use the nonlocal statement in your nested function.
-
By declaring a variable as nonlocal, you enable the inner function to modify it rather than creating a new local instance.
Surface Forms
Morphology
Etymology
Nonlocal as a Python keyword uses non- 'not' and local 'inside this function' to mean a name is 'not local' to the inner function but belongs to the nearest outer function, so the inner code can change that variable.