liveBook · Manning

Nonlocal statement

As explained in 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.

When a nested function must update state owned by its enclosing function, use nonlocal. It makes assignments target the enclosing binding instead of creating a new local one. Python still resolves names through the LEGB sequence: local, enclosing, global, and built-ins. section 6.5

Counting calls with enclosed state

def foo(): call_counter = 0 def bar(y): nonlocal call_counter call_counter += 1 return f'y = {y}, call_counter = {call_counter}' return bar b = foo() for i in range(10, 100, 10): print(b(i)) Each call to b updates the same call_counter in foo, producing counts from 1 through 9. section 6.5

def foo():
    call_counter = 0                                     #1
    def bar(y):
        nonlocal call_counter                            #2
        call_counter += 1                                #3
        return f'y = {y}, call_counter = {call_counter}'
    return bar

b = foo()
for i in range(10, 100, 10):                             #4
    print(b(i))                                          #5

Inspect the complete nested-function example, including the declaration, mutation, returned function, and repeated calls. section 6.5

How Python Workout: 50 ten-minute exercises covers it

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 it assumes
Assumes nested functions and variable scope, then distinguishes enclosing bindings from local and global bindings.
What you can do after
Apply it via Python to preserve and update enclosing-function state across nested-function calls.
How it connects
Connects nested functions, closures, LEGB scoping, and the global statement.

Also explained in

Compare how 2 books explain nonlocal statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.