Sub topic 10
Rebinding an enclosing name with nonlocal
This chapter assumes you know how to define and call functions, how the LEGB lookup rule works, and why assigning to a name inside a function makes that name local. It also assumes you have seen the global statement. Here you will use nonlocal to rebind a name that belongs to an enclosing function.
The problem: closures can read but not rebind
An inner function can read names from the function that encloses it. It cannot rebind them with a plain assignment. The same rule that causes UnboundLocalError with globals applies here. 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 means total = total + n. That is an assignment, so total becomes local to add. The right-hand side then reads a local total that has no value yet, and the call fails.
The fix: declare the name nonlocal
The nonlocal statement tells Python that a name refers to a binding in the nearest enclosing function scope. Assignments to that name then rebind the enclosing variable.
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 variable total lives on after make_counter returns, because the inner function keeps a reference to it. Each call to make_counter() creates a new total, so separate counters do not share state.
How nonlocal differs from global
The two statements look alike but target different scopes.
| Statement | Target scope | Name must already exist? |
|---|---|---|
| `global x` | Module scope | No. The assignment can create it. |
| `nonlocal x` | Nearest enclosing function scope | Yes. Python raises `SyntaxError` at compile time if no enclosing function binds it. |
Because nonlocal never reaches module scope, it cannot rebind a global name. Using it at module level, or naming a variable that no enclosing function defines, is a SyntaxError.
When you do not need nonlocal
You need nonlocal only to rebind. Mutating an object that the enclosing function holds works without it, because the name is not rebound.
def make_log():
entries = []
def record(message):
entries.append(message)
return len(entries)
return record
log = make_log()
print(log("start"))
print(log("stop"))
# Output:
# 1
# 2This is the same distinction as mutation versus rebinding for globals. Some programmers use a list or a small class to hold state instead of nonlocal. Both are fine. For a single counter, nonlocal is shorter and clearer.
Common errors
- Forgetting the declaration and getting
UnboundLocalErroron an augmented assignment such as+=. - Writing
nonlocalfor a name that is only defined at module level. Useglobalfor that case. - Placing
nonlocalafter the name is used in the same function. The declaration must come before any use of the name in that function body.
Exercise
The function below raises an error when tick() is called. Explain why, and rewrite make_clock so that tick() returns 1, then 2, then 3.
def make_clock():
seconds = 0
def tick():
seconds = seconds + 1
return seconds
return tick
Show answer
The assignment seconds = seconds + 1 makes seconds local to tick, so the right-hand side reads a local variable before it has a value, which raises UnboundLocalError. Add nonlocal seconds as the first line of tick:
def make_clock():
seconds = 0
def tick():
nonlocal seconds
seconds = seconds + 1
return seconds
return tick
Exercise
Does entries.append(message) in the record function need a nonlocal entries declaration? Why or why not?
Show answer
No. The call mutates the list object that entries refers to. It never assigns to the name entries, so the name is not made local and no rebinding happens.