TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
nonlocal keyword in Python is used within nested functions to declare that a variable refers to a previously bound variable in the nearest enclosing lexical scope, excluding the global scope. It instructs the Python compiler to bypass the local namespace during variable assignment and instead bind the identifier to an existing variable in a parent function’s namespace.
Syntax
Scope Resolution and Rebinding
In Python’s LEGB (Local, Enclosing, Global, Built-in) scope resolution, reading a variable automatically searches up the scope chain. However, assigning a value to a variable defaults to creating or updating a variable in the Local scope. Withoutnonlocal, an assignment operation inside a nested function creates a new local variable that shadows the variable in the enclosing scope. The nonlocal statement overrides this default behavior, granting write access (rebinding capability) to the Enclosing scope.
Mechanical Example
Technical Constraints
- Compile-Time Binding Requirement: The variable declared as
nonlocalmust be bound in an enclosing function’s local scope. Because Python determines local variables for the entire function block at compile time, thenonlocaldeclaration is resolved during compilation, not at runtime. You cannot usenonlocalto dynamically create a new variable in a parent scope. However, because it is a compile-time declaration, the variable’s assignment in the enclosing scope can textually appear after the nested function definition, provided it is bound within that enclosing function’s local scope.
- Exclusion of Global Scope:
nonlocalstrictly searches enclosing function scopes. It will not resolve to variables defined in the global module scope. If the compiler exhausts all enclosing function scopes and hits the global scope without finding the variable, it raises aSyntaxError. To modify global variables, theglobalkeyword must be used instead. - Exclusion of Local Scope: A variable cannot be declared as
nonlocalif it has already been treated as a local variable in the current block. Thenonlocaldeclaration must precede any assignment to that variable within the nested function.
Master Python with Deep Grasping Methodology!Learn More





