liveBook · Manning

Nonlocal statement

A nonlocal statement makes a name assigned in a nested Python function refer to a binding in an enclosing function scope.

How 2 Manning books explain it

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

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.