Nonlocal statement
A nonlocal statement makes a name assigned in a nested Python function refer to a binding in an enclosing function scope.
Python Workout, Second Edition
The nonlocal keyword declares that assignments in a nested function refer to a name in an enclosing function scope.
- How it is used
- Uses nonlocal to maintain mutable state across calls to a nested function.
- How deep it goes
- Explains LEGB lookup and demonstrates state updates, but stops short of broader closure internals.
- Examples
- Demonstrates a returned counter function whose output increments from one call to the next.
- What you can do after
- Apply nonlocal to update enclosing-function state from a nested Python function.
Read how Python Workout, Second Edition explains nonlocal statement →
Python Workout: 50 ten-minute exercises
The nonlocal keyword declares that assignments in a nested function target a binding in an enclosing function rather than a new local binding.
- How it is used
- Updates state in an enclosing function from a nested function.
- How deep it goes
- Explains name lookup and demonstrates mutation through a complete nested-function counter, without deeper implementation details.
- Examples
- Uses a returned counter function that records calls while processing values from 10 through 90.
- What you can do after
- Apply it via Python to preserve and update enclosing-function state across nested-function calls.
Read how Python Workout: 50 ten-minute exercises explains nonlocal statement →
Related concepts
- scopeconfigures · Scope is the region of a program in which names are visible and can be resolved according to the language’s lookup rules.
- global statementcontrasts with · A global statement is a Python declaration that makes specified names in a function refer to bindings in the module-level global namespace.
- enclosing functionconfigures · An enclosing function is a function whose body contains a nested function definition and provides a surrounding lexical scope for it.
- assignmentcontrasts with · Assignment is a programming-language operation that binds or stores an evaluated value in a variable, property, or other assignable location.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

