Lesson · Functional Programming Tools
Closures
55 min readClosures
A closure is a function that retains access to names from an enclosing scope after that scope has returned. Closures are compact tools for factories and state, with a famous late-binding pitfall.
Learning goals
- Explain how
next_valuestill reachescountaftermake_counterhas returned. - Trace the closure cell that holds
countand say why two counters from one factory stay independent. - Use
nonlocalto rebind an enclosing name and predict the error that appears without it. - Show how a default parameter captures a loop variable's current value per closure.
- Decide when a stateful closure is a clearer design than an object with attributes.
Mental model
Two calls to make_counter create two cells, so the counters never share state, while every call of one counter advances the same single cell.
Mental model
read it top to bottom
make_counter(10) runs and binds count = 10 ↓ next_value is created and remembers count's cell ↓ make_counter returns; the cell survives with the function ↓ each call to counter() reads and rebinds that same cell
Core idea
A closure is a function plus the enclosing bindings its body still needs, kept alive in cells instead of copied at definition time. That one fact explains the stateful counter (each call rebinds the cell), separate factory results staying independent (each call gets fresh cells), and the late-binding loop trap (every closure made in one scope shares that scope's cell).
Enclosing scope
Nested functions can read bindings from lexically enclosing function scopes. nonlocal allows controlled rebinding of such a name.
Captured variables
A closure refers to an enclosing binding through a closure cell. If that binding changes, later calls can observe the new value rather than a frozen snapshot.
nonlocal
nonlocal targets a binding in the nearest enclosing function scope. It is useful for stateful closures when mutating an object is not enough.
Stateful closures
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
Late-binding closure trap
Closures created in a loop commonly capture the same loop variable binding, so they later observe its final value. Bind the current value explicitly, for example through a default parameter, when a snapshot is intended.
Walkthrough
make_counter(10)runs once: it bindscountto10, definesnext_valuewithout calling it, and returns the function object.nonlocal counttells the compiler thatcount += 1rebinds the enclosing name rather than creating a local one. Delete that line and the same statement raisesUnboundLocalError, because the compiler then treatscountas local.counter()is a call tonext_value, so the first call rebinds the shared cell to11and returns it; the second returns12. What survives between calls is the cell, not a snapshot of10.- Predict before running: the two printed numbers, and what a third call would return.
Experiments to try
- Create
other = make_counter(100)and interleave calls withcounter(); record both sequences and explain why they do not interfere. - Delete the
nonlocalline and run again; read theUnboundLocalErrorand name the local binding the compiler assumed. - Add
def peek(): return countinsidemake_counter, return both functions, and check thatpeekobserves the updatesnext_valuemakes. - Build a list of lambdas in a for loop, first as
lambda: iand then aslambda value=i: value; run both lists and explain the difference with the shared-cell rule.
Common mistakes
- Omitting
nonlocalfor a name that is only read: reads work, so the defect appears later, when an assignment is added and the call starts raisingUnboundLocalError. - Creating closures in a loop without binding the loop variable per iteration: every closure shares one cell and reports the final value.
- Treating the captured binding as a frozen snapshot: the closure sees later rebinds, which is why
counter()increments instead of always returning11. - Assuming every nested function is a closure: one that uses only its own parameters captures nothing, and its
__closure__staysNone.
Practice: Easy
- Run the worked example, then print
counter.__closure__[0].cell_contentsand name the variable whose cell it is. - Copy
make_counterinto a variant that adds two per call (count += 2) and record the new sequence of returned values. - Call
make_counter()with no argument and explain where the default0ends up and what the first call returns.
Practice: Medium
- Write
make_accumulator(total=0)whose returned function adds its argument tototaland returns the new total; build two accumulators and show they do not share state. - Explain the difference between
lambda: iandlambda i=i: iwhen each is defined in a for loop, and demonstrate the difference on one list. - Extend
make_counterto return a(next_value, reset)pair of closures over the same cell; define what each function does and test an interleaved sequence.
Practice: Hard
- Build a
make_histogram()factory returningrecord(value)andreport()closures over one dictionary; define what the dictionary holds, when it grows, and whetherreportreturns a copy. - Design a memoizing factory with its own dictionary cell instead of
functools.lru_cache; state where the cache lives and why it survives between calls. - Support the independence claim from the mental model with a planned experiment: two counters from the same factory, interleaved calls, and a table of call order against expected output written before you run anything.
Lesson checklist
- I can explain what a closure cell holds and when it is created.
- I can predict the output of two interleaved counters built by the same factory.
- I can recognize the late-binding loop trap and fix it with a default parameter.
- I can decide when
nonlocalis required and what error appears without it.
Remember
A closure keeps the enclosing bindings its body still reads, and those bindings live in cells shared with the outer function rather than copied into the inner function. `nonlocal` is how the inner function rebinds the cell, which is why counter state survives between calls while separate factory calls stay independent. Closures created in one loop share one cell, the trap behind the default-parameter workaround.
Interview angles
What is the main purpose of **Enclosing scope**?+
Nested functions can read bindings from lexically enclosing function scopes. nonlocal allows controlled rebinding of such a name.
What should you pay attention to when using **Captured variables**?+
A closure refers to an enclosing binding through a closure cell. If that binding changes, later calls can observe the new value rather than a frozen snapshot.
How does **nonlocal** fit into this lesson?+
nonlocal targets a binding in the nearest enclosing function scope. It is useful for stateful closures when mutating an object is not enough.
Why does a closure created in a for loop often report only the last value?+
Each iteration rebinds the same loop variable, so all closures created in that scope capture the same cell. When they run after the loop, they all read the final binding. Bind the current value per iteration, for example with a default parameter such as lambda value=i: value.