Python nonlocal keyword
last modified November 29, 2026 Python 3.15
In this article we show how to use the nonlocal keyword in
Python.
A function can be defined inside another function. The inner function can
read the variables of the enclosing function, but assigning to such a
variable normally creates a new local variable of the inner function. The
nonlocal statement declares that a name refers to the
variable of the nearest enclosing function, so that the inner function can
rebind it.
nonlocal is the counterpart of global, which
does the same for module variables and is covered in
Python global keyword. The general
rules for name lookup are described in
Python variable scope.
Reading an enclosing variable
A nested function can read the variables of the function that contains it. No declaration is needed for reading.
def report():
title = "Daily report"
def header():
print("=" * len(title))
print(title)
print("=" * len(title))
header()
print("all systems running")
report()
The header function uses title, which is a
local variable of report. Python does not find the name among
the locals of header and looks it up in the enclosing
function.
$ python reading.py ============ Daily report ============ all systems running
Assignment creates a local variable
When a function assigns to a name anywhere in its body, the name is local to that function. This decision is made when the function is compiled, and it applies to the whole body, even to the lines before the assignment.
def process(tasks):
done = 0
def finish(task):
print("finished", task)
done += 1
for task in tasks:
finish(task)
print("done:", done)
process(["backup", "cleanup"])
done += 1 is an assignment, so done is a local
variable of finish. The augmented assignment first reads the
local variable, which has no value yet, and Python raises an
UnboundLocalError. The traceback shows that the error occurs
during the first call; the first task was already printed.
$ python unbound.py
finished backup
Traceback (most recent call last):
File "/home/user/nonlocal-keyword/unbound.py", line 13, in <module>
process(["backup", "cleanup"])
~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/nonlocal-keyword/unbound.py", line 9, in process
finish(task)
~~~~~~^^^^^^
File "/home/user/nonlocal-keyword/unbound.py", line 6, in finish
done += 1
^^^^
UnboundLocalError: cannot access local variable 'done' where it is not associated with a value
The nonlocal statement
The nonlocal statement tells the compiler that a name belongs
to an enclosing function. Assignments then rebind the variable of the
enclosing function instead of creating a local one.
def process(tasks):
done = 0
def finish(task):
nonlocal done
print("finished", task)
done += 1
for task in tasks:
finish(task)
print("done:", done)
process(["backup", "cleanup", "report"])
With nonlocal done, each call of finish
increases the variable of process. After the loop,
process sees the updated value. The statement must appear
before the name is used in the function; it is usually the first line of
the body.
$ python nonlocal_statement.py finished backup finished cleanup finished report done: 3
Mutating versus rebinding
nonlocal is needed only to rebind a name. Changing a mutable
object in place, for example appending to a list, does not assign to the
name and works without any declaration.
def shopping():
items = []
def add(item):
items.append(item)
def clear():
nonlocal items
items = []
add("bread")
add("milk")
print(items)
old = items
clear()
add("eggs")
print(items)
print(old)
shopping()
add calls items.append, which modifies the list
that items refers to. clear assigns a new list to
items, so it needs nonlocal. The old list still
exists under the name old and keeps its contents; only the
name items was moved to the new list.
$ python mutate_rebind.py ['bread', 'milk'] ['eggs'] ['bread', 'milk']
The nearest enclosing function
When functions are nested several levels deep, nonlocal
refers to the nearest enclosing function that has a variable of that name.
Outer functions with the same name are not affected.
def level1():
x = "level1"
def level2():
x = "level2"
def level3():
nonlocal x
x = "changed by level3"
level3()
print("level2 x:", x)
level2()
print("level1 x:", x)
level1()
level3 declares x as nonlocal. Both
level2 and level1 have an x; the
nearer one, in level2, is changed. The variable in
level1 keeps its value.
$ python nearest.py level2 x: changed by level3 level1 x: level1
Local, nonlocal, and global
A name can exist at the module level, in an enclosing function, and in an inner function at the same time. Which of the three variables an assignment changes depends on the declaration.
mode = "module"
def outer():
mode = "outer"
def use_local():
mode = "local"
print("use_local:", mode)
def use_nonlocal():
nonlocal mode
mode = "set by use_nonlocal"
def use_global():
global mode
mode = "set by use_global"
use_local()
print("outer:", mode)
use_nonlocal()
print("outer:", mode)
use_global()
print("outer:", mode)
outer()
print("module:", mode)
Without a declaration, use_local creates its own variable and
nothing else changes. use_nonlocal rebinds the variable of
outer. use_global skips outer
entirely and rebinds the module variable, so outer still sees
the value set by use_nonlocal.
$ python three_scopes.py use_local: local outer: outer outer: set by use_nonlocal outer: set by use_nonlocal module: set by use_global
Parameters of the enclosing function
Parameters are local variables of their function. A nested function can therefore declare a parameter of the enclosing function as nonlocal.
def launch(seconds):
def tick():
nonlocal seconds
print("T minus", seconds)
seconds -= 1
while seconds > 0:
tick()
print("lift-off, seconds =", seconds)
launch(3)
The seconds parameter of launch is decreased by
the nested tick function. The while loop in
launch sees the new value after each call and ends when it
reaches zero.
$ python parameters.py T minus 3 T minus 2 T minus 1 lift-off, seconds = 0
No binding for nonlocal
A nonlocal name must already exist in an enclosing function.
Unlike global, the statement cannot create a new variable,
and it never refers to module variables.
total = 0
def add_all(numbers):
def add(n):
nonlocal total
total += n
for n in numbers:
add(n)
add_all([1, 2, 3])
print(total)
total is a module variable, and add_all has no
variable of that name. The compiler reports a SyntaxError
before any code runs. Using nonlocal at the module level is a
syntax error as well. Here, global total would be the correct
declaration, or better, add_all could keep its own total and
return it.
$ python no_binding.py
File "/home/user/nonlocal-keyword/no_binding.py", line 7
nonlocal total
^^^^^^^^^^^^^^
SyntaxError: no binding for nonlocal 'total' found
Keeping state between calls
When the outer function returns the inner function, the enclosing
variables stay alive with it. The inner function can use
nonlocal to update them, so they keep their values between
calls. Such a function is called a closure.
def make_detector(name):
last = None
def update(value):
nonlocal last
if value != last:
print(f"{name}: {last} -> {value}")
last = value
return update
door = make_detector("door")
light = make_detector("light")
for state in ["closed", "closed", "open", "open", "closed"]:
door(state)
light("off")
light("on")
door("closed")
make_detector returns an update function that
remembers the last value it has seen. It prints a line only when the value
changes and then stores the new value. Each call of
make_detector creates a new last variable, so the
door and light detectors are independent. Closures are covered in
Python closures.
$ python change_detector.py door: None -> closed door: closed -> open door: open -> closed light: None -> off light: off -> on
Several functions sharing state
Several inner functions can declare the same nonlocal variables. They then share the state, and each of them sees the changes made by the others.
def make_account(owner, balance=0):
history = []
def deposit(amount):
nonlocal balance
balance += amount
history.append(f"+{amount}")
def withdraw(amount):
nonlocal balance
if amount > balance:
print(f"{owner}: insufficient funds for {amount}")
return
balance -= amount
history.append(f"-{amount}")
def statement():
print(f"{owner}: {balance} {history}")
return deposit, withdraw, statement
deposit, withdraw, statement = make_account("Martin", 100)
deposit(50)
withdraw(30)
withdraw(500)
statement()
deposit and withdraw both rebind
balance, which is a parameter of make_account.
The history list is only mutated, so it needs no declaration.
statement only reads the variables. The three functions are
returned as a tuple and unpacked into three names. When the shared state
grows, a class is usually a clearer design; see
Python methods.
$ python account.py Martin: insufficient funds for 500 Martin: 120 ['+50', '-30']
Source
The nonlocal statement, Resolution of names, PEP 3104 – Access to names in outer scopes
In this article we have read variables of enclosing functions, seen why assignment without a declaration raises UnboundLocalError, rebound enclosing variables with nonlocal, compared mutation with rebinding, nonlocal with global, and used nonlocal variables to keep state between calls. See also Python global keyword, Python closures, and Python variable scope.
Author
List all Python tutorials.