Sub topic 10
Rebinding an enclosing name with nonlocal
This chapter assumes you can define and call functions, read a traceback, and that you know the LEGB lookup rule and why assigning to a name inside a function makes it local (the UnboundLocalError case). You also need to have seen the global statement. Here you will see how a nested function rebinds a name that belongs to an outer function, and where that technique stops working.
The problem: closures can read but not rebind
A nested function can read names from the function that encloses it. This works through the "E" in LEGB. The same assignment rule from the earlier chapters still applies, though. If the inner function assigns to a name, Python treats that name as local to the inner function for its whole body.
def make_counter():
total = 0
def add(n):
total += n
return total
return add
counter = make_counter()
counter(2)
# UnboundLocalError: cannot access local variable 'total' where it is not associated with a valueThe statement total += n is an assignment, so total is local to add. The augmented assignment first reads total, and the local total has no value yet. The total in make_counter is never touched. The exact error wording varies between Python versions.
The global statement cannot fix this. total is not a module-level name, and global total would point at the module namespace instead of at make_counter.
The nonlocal statement
The nonlocal statement tells Python that a name in the current function refers to a binding in the nearest enclosing function scope. Assignments to that name then rebind the outer variable instead of creating a local one.
def make_counter():
total = 0
def add(n):
nonlocal total
total += n
return total
return add
counter = make_counter()
print(counter(2))
print(counter(3))
# Output:
# 2
# 5The state lives in total, which belongs to the call of make_counter that created counter. The function make_counter has already returned, but total stays alive because add still refers to it. This pairing of a function with the variables it captured is a closure.
Each call to make_counter creates a fresh total, so closures made by separate calls do not share state:
def make_counter():
total = 0
def add(n):
nonlocal total
total += n
return total
return add
a = make_counter()
b = make_counter()
print(a(10))
print(b(1))
print(a(5))
# Output:
# 10
# 1
# 15What Python does with the declaration
The declaration is resolved when the code is compiled, not when it runs. Three consequences follow:
- The compiler looks outward through the enclosing function scopes for a binding of that name. If it finds none, it raises a
SyntaxErrorbefore any code in the file runs. - The declaration applies to the whole body of the inner function. Use of the name before the
nonlocalline is aSyntaxError. - Reading the name needs no declaration. You only need
nonlocalwhen the function rebinds the name, which includes=,+=,fortargets,import,def,class, anddel.
You can look at the result using attributes that every function has:
def make_counter():
total = 0
def add(n):
nonlocal total
total += n
return total
return add
counter = make_counter()
counter(2)
counter(3)
print(counter.__code__.co_freevars)
print(counter.__closure__[0].cell_contents)
# Output:
# ('total',)
# 5co_freevars lists the names the function takes from an enclosing scope. __closure__ holds one cell object per free variable. A cell is a small box that the outer function and the inner function both point at. When add rebinds total, it changes what the cell holds. This is why the outer function also sees the new value.
Which enclosing scope is used
When functions are nested more than one level deep, nonlocal picks the nearest enclosing function that binds the name. Intermediate functions that never assign the name do not need any declaration.
def outer():
level = "outer"
def middle():
def inner():
nonlocal level
level = "changed by inner"
inner()
return level
result = middle()
return result, level
print(outer())
# Output: ('changed by inner', 'changed by inner')middle does not assign level, so the name resolves to outer's variable. inner rebinds that variable.
If middle also assigned level, the nearest binding would be middle's, and inner would change that one instead:
def outer():
level = "outer"
def middle():
level = "middle"
def inner():
nonlocal level
level = "changed by inner"
inner()
return level
return middle(), level
print(outer())
# Output: ('changed by inner', 'outer')Adding an assignment in an intermediate function therefore changes what a deeper nonlocal refers to. This is a common source of confusion when someone edits a function in the middle of a chain.
Rules and common errors
The compiler rejects these cases with a SyntaxError:
count = 0
def bump():
nonlocal count
count += 1
# SyntaxError: no binding for nonlocal 'count' foundThe name count exists only at module level. nonlocal never reaches the global scope, so use global there. A misspelled name gives the same error, which is helpful because the typo is caught at compile time.
nonlocal x
# SyntaxError: nonlocal declaration not allowed at module levelTwo more restrictions:
- A parameter cannot also be declared
nonlocalin the same function. The parameter is already local. - You cannot use the name in the function before the
nonlocalstatement.
A runtime failure is still possible. If the outer variable has not been assigned yet when the inner function reads it, you get a NameError. A function that rebinds a name with only = does not need the value to exist first:
def outer():
def setter():
nonlocal value
value = 1
value = 0
setter()
return value
print(outer())
# Output: 1The binding of value appears later in outer's body, and that is enough for the compiler to accept the declaration.
Comparing nonlocal and global
| Aspect | `global name` | `nonlocal name` |
|---|---|---|
| Target scope | Module namespace | Nearest enclosing function scope |
| Name must already be bound by a compile-time assignment | No, the name can be created by the function | Yes, an enclosing function must bind it |
| Works at module level | Allowed but has no effect | `SyntaxError` |
| Typical use | Module-wide settings or counters | Private state in a closure |
| State lifetime | Lives as long as the module | Lives as long as the closure exists |
Alternatives that avoid nonlocal
You do not always need nonlocal. Mutation does not rebind the name, so a mutable container can hold the state:
def make_counter():
state = {"total": 0}
def add(n):
state["total"] += n
return state["total"]
return add
counter = make_counter()
print(counter(2))
print(counter(3))
# Output:
# 2
# 5Here state["total"] += n is an item assignment. It mutates the dictionary and never rebinds state, so no declaration is required. The trade-off is that the state is a visible container, and the code reads less directly than nonlocal total.
Two other options are worth knowing. A small class with an instance attribute holds the state more explicitly, and it is easier to test and extend once you have more than a couple of values. A generator keeps state in its local variables between yield points. Pick nonlocal when the state is small, private, and tied to a single function.
A larger example
A closure can rebind several outer names with one declaration. This running average keeps a count and a sum:
def make_averager():
count = 0
total = 0.0
def update(value):
nonlocal count, total
count += 1
total += value
return total / count
return update
avg = make_averager()
print(avg(10))
print(avg(20))
print(avg(30))
# Output:
# 10.0
# 15.0
# 20.0Both names appear in one nonlocal statement, separated by commas. Other functions defined inside make_averager could share the same two variables, and they would all see the same cells.
Summary of the working model
- Assigning to a name inside a function makes it local unless you declare otherwise.
nonlocal nameredirects that name to the nearest enclosing function scope that binds it.- The check happens at compile time, so mistakes show up as
SyntaxErrorbefore the code runs. - The shared variable lives in a cell, which keeps it alive after the outer function returns.
- Mutating an object in an outer scope does not need
nonlocal. Rebinding the name does.
Exercise
The function below is meant to return a function that counts how many times it has been called, but calling it raises an error. Describe the error, explain why it happens, and give the one-line fix. def make_calls(): calls = 0 def tick(): calls = calls + 1 return calls return tick
Show answer
The call raises UnboundLocalError. Because tick assigns to calls, Python treats calls as a local variable of tick for the whole body, and the right-hand side reads it before it has a value. The fix is to add nonlocal calls as the first line of tick, so the assignment rebinds the variable in make_calls instead.
Exercise
Predict the output of this program and explain which variable each function changes. def outer(): x = "outer" def middle(): x = "middle" def inner(): nonlocal x x = "inner" inner() return x return middle(), x print(outer())
Show answer
It prints ('inner', 'outer'). The nonlocal x in inner resolves to the nearest enclosing function that binds x, which is middle, not outer. So inner rebinds middle's x, and middle returns "inner". The x in outer is never changed, so outer returns "outer" for the second value.
Exercise
Why does this code fail before it prints anything, and what should you use instead? count = 0 def bump(): nonlocal count count += 1 print("start")
Show answer
It raises SyntaxError: no binding for nonlocal 'count' found. The error appears at compile time, so "start" is never printed. The name count is bound only at module level, and nonlocal looks only at enclosing function scopes. Use global count to rebind a module-level name.