liveBook · Manning

Nonlocal statement

Also called nonlocal keyword

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 →

Also covered in

What to know first

Related concepts

Questions about nonlocal statement

What is nonlocal statement?

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

Which Manning books explain nonlocal statement?

Python Workout, Second Edition and Python Workout: 50 ten-minute exercises.

What should I know before learning nonlocal statement?

Manning books that teach nonlocal statement usually introduce decorator, namespace, assignment and scope first.

What is the difference between nonlocal statement and global statement?

A nonlocal statement makes a name assigned in a nested Python function refer to a binding in an enclosing function scope. A global statement is a Python declaration that makes specified names in a function refer to bindings in the module-level global namespace.

What is nonlocal statement a kind of?

Nonlocal statement is a kind of statement. A statement is a syntactic unit in a programming or query language that expresses an instruction, declaration, or control operation for a processor to execute.

What is nonlocal statement also called?

Nonlocal statement is also called nonlocal keyword.

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.