A closure is a function that retains access to bindings from an enclosing function, even after that enclosing call has returned.
Inspect remembered state, nonlocal updates and the difference between sharing a binding and capturing a value at creation.
A callback can run after the function that created it has returned. What does it remember: the old value, or a binding that can still change? Follow the captured cell to answer that question. Then use the same mechanism for independent counters, shared statistics, and callbacks that must keep different settings.

Tag log lines by channel
A function defined inside another function can read the outer function's variables — including after the outer call has finished:
By the time access(...) runs, make_tagger("access") has already returned —
its local variables should be gone. Python notices tag uses prefix and puts
it in a cell instead of discarding it; tag keeps a reference to that cell:
The cell holds the variable, not a frozen value — so if it changes before the inner function runs, the inner function sees the change:
def build():
limit = 10
def show():
return limit
limit = 99
return show
print(build()())Preparing this topic’s interactive investigation…
Numbering rows as they pass
A counter that numbers rows so a bad one can be reported as "row 4812" instead
of "some row". The obvious attempt fails the same way a bare global mistake
would:
UnboundLocalErrorRun it and read the error name. Add one line so bump rebinds the enclosing count instead of creating its own.
nonlocal count tells Python the name belongs to the nearest enclosing function
that has one, so count += 1 rebinds the cell instead of creating a fresh local:
Mutating an object inside the cell is not rebinding, so it needs no
nonlocal at all:
You only need nonlocal when the name sits on the left of =, += or
similar — exactly as with global.
Scale three sensor channels
Each call to a factory runs its body again and builds fresh cells, so the local integer counters in these separate calls have independent state:
def make_counter():
count = 0
def bump():
nonlocal count
count += 1
return count
return bump
rows = make_counter()
errors = make_counter()
rows(); rows(); rows()
errors()
print(rows(), errors())But three functions built in the same call share whatever cell that call created — which is exactly the trap that catches almost everyone once:
def build_scalers():
scalers = []
for channel in range(3):
scalers.append(lambda x: x * channel)
return scalers
print([f(10) for f in build_scalers()])Step through it and read cell_contents for each function. The numbers are
real, taken from the functions themselves:
Here is the picture the trace is describing:
Two standard fixes: a factory gives each function its own captured cell; a default argument stores a value on the function instead of capturing that name:
Calling make_scaler separately for each function is the clean fix. The default
argument trick works too — it evaluates c at definition time, not call time —
but it adds a parameter a caller could override by accident.
Separate the cell from the object inside it
Fresh factory calls create fresh bindings, but their cells can still refer to the same mutable input. The identity lesson therefore still applies inside a closure; “private state” is not an automatic copy.
Both return 9, although the cells are different (False). The cells each
hold a reference to the same dictionary. Rebinding the caller's shared name
to a new dictionary would have a different effect: the closures would still
reach the old dictionary.
Choose the intended contract before fixing the code. A live configuration
reader should observe edits; a snapshot reader should capture an immutable
value such as limit = settings["limit"] when the factory runs. A shallow
dictionary copy isolates only its outer mapping, not nested mutable values.
Apply that distinction to delayed callbacks: build two readers, mutate the original configuration, then rebind the original name. Predict each result before executing. If the values surprise you, inspect the object reached by the cell, not merely the number of closures you created. The counter exercises use integers and fresh local totals, which is why their independent state is simple to reason about.
Track call counts with a class instead
A class can hold the same state:
Rule of thumb: one operation on the remembered state, reach for a closure — it's shorter, and there's no attribute for outside code to poke at by accident. Several operations sharing one state, or code outside that needs to inspect it, write a class. Closures can share one cell between several inner functions returned together — you'll use exactly that in the exercises below — but past two or three functions, a class reads better.
Quick practice
def make_counter():
count = 0
def bump():
nonlocal count
count += 1
return count
return bump
a = make_counter()
b = make_counter()
a(); a()
print(a(), b())def make_adders():
return [lambda x: x + i for i in range(3)]
print([f(10) for f in make_adders()])🎯 Your turn
Some of Quarry's stages count in steps — a sampler that keeps every fifth row numbers them 5, 10, 15, and so on.
Write make_counter(step), a factory returning a function. Each call adds
step to a running total that starts at 0, and returns the new total. Then
write counter_readings(step, calls): build one counter and return what it
returns on each of calls calls.
counter_readings(1, 3)→[1, 2, 3]counter_readings(5, 4)→[5, 10, 15, 20]counter_readings(2, 0)→[]
Hint: the inner function rebinds the total, so it needs nonlocal. Build the
counter once, outside the loop that calls it.
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write make_greeter(greeting) returning a function that takes a name and returns f"{greeting}, {name}!". Then write greet_with(greeting, name) that builds a greeter and calls it once.
Write make_accumulator() returning a function add(amount) that adds amount to a running total and returns the new total. Then running_totals(amounts) feeds every amount to one accumulator and returns the list of totals it reported.
Write channel_outputs(n, reading). Build a list of n functions in a loop, where function i multiplies its argument by i. Return a list of every function applied to reading. The late-binding trap will make every function use the last i unless you give each one its own cell.
Quarry refuses to read more than max_reads batches from any one source per run. Write make_limiter(max_reads) returning allow(source), which returns True while that source has been allowed fewer than max_reads times, and False after. Then limiter_verdicts(max_reads, sources) returns the list of verdicts for each source in order.
Write make_stats() returning a pair of functions (add, summary) that share the same state. add(x) records a value; summary() returns {"count": n, "total": t, "min": lo, "max": hi}, with min/max as None when nothing was added. Then stats_after(values) adds every value and returns the summary.
A teammate builds handlers = [lambda row: row[i] for i in range(3)] and finds that every handler returns column 2. Explain to them what is actually happening, in terms of cells, and give two ways to fix it — saying which you prefer and why.