The Late-Binding Closure Trap
Concepts covered: Functions
A closure reads a captured variable at the moment it runs, from the cell it shares with the enclosing function. Create closures inside a loop and they all capture the same loop variable, because the loop rebinds a single name on every pass. Call them after the loop and every one of them sees the loop's final value.
Here is the pricing bug from the start of the lesson. Each price function should apply its own city's surge multiplier, and the last 2 prints check what the functions share.
def build_pricers(multipliers):
pricers = {}
for city, rate in multipliers.items():
def price(fare):
return fare * rate
pricers[city] = price
return pricers
surge = {"Chicago": 1.2, "Boston": 1.5, "Austin": 1.8}
pricers = build_pricers(surge)
for city, fn in pricers.items():
print(city, fn(10))
chicago, austin = pricers["Chicago"], pricers["Austin"]
print(chicago is austin)
print(chicago.__closure__[0] is austin.__closure__[0])Chicago 18.0 Boston 18.0 Austin 18.0 False True
The False confirms there are 3 distinct function objects in the dict. The True shows what they have in common: the same cell for rate. There is a single rate variable in build_pricers, the loop rebinds it 3 times, and none of the functions runs until the loop is over and rate holds 1.8.
When the trap fires and when it doesn't
The bug needs 2 ingredients: a closure created inside a loop, and a call that happens after the loop variable has moved on. Call price(10) inside the loop body, right after the def, and you get 12.0, 15.0 and 18.0, because each call reads rate while it still holds the current city's multiplier. The trap shows up in code that stores functions for later: dicts of pricers, lists of validation rules, handlers registered to run at the end of a job.
Signs of the trap in a code review
- A def inside a for loop whose body reads the loop variable
- Functions stored in a list or dict and called after the loop ends
- Every stored function returning the result meant for the last item
Three ways to bind each value now
Each fix moves the binding from call time to creation time, so every function holds its own value.
Fix 1: a default argument
Default values are evaluated once, when the def statement runs. Writing def price(fare, rate=rate) copies the current rate into that function's default on each pass, so the function stops reading the shared cell.
Fix 2: a factory function
Move the def into a factory such as make_pricer(rate). Every factory call runs in its own scope with its own rate cell, and nothing rebinds that cell after the call returns.
Fix 3: partial
partial(multiply, rate) evaluates rate immediately and stores the value in the partial object's .args. All 3 fixes, side by side in a single run:
from functools import partial
surge = {"Chicago": 1.2, "Boston": 1.5, "Austin": 1.8}
def make_pricer(rate):
def price(fare):
return fare * rate
return price
def multiply(rate, fare):
return fare * rate
with_default, with_factory, with_partial = {}, {}, {}
for city, rate in surge.items():
def price(fare, rate=rate):
return fare * rate
with_default[city] = price
with_factory[city] = make_pricer(rate)
with_partial[city] = partial(multiply, rate)
for city in surge:
print(city, with_default[city](10), with_factory[city](10), with_partial[city](10))Output:
Chicago 12.0 12.0 12.0 Boston 15.0 15.0 15.0 Austin 18.0 18.0 18.0
| Fix | When the value is bound | Trade-off |
|---|---|---|
| Default argument `rate=rate` | When the `def` runs, once per pass | A caller can pass `rate=` and override it |
| Factory `make_pricer(rate)` | When the factory is called, in a new scope | An extra function to name and read |
| `partial(multiply, rate)` | When the partial object is created | Needs a function whose first parameter is the rate, or a keyword |
The default-argument fix leaves rate as a real parameter, so a caller who passes a second argument replaces the stored multiplier and gets no error. The stored value sits in the function's __defaults__ tuple, the counterpart of __closure__ for this fix:
surge = {"Chicago": 1.2, "Boston": 1.5}
pricers = {}
for city, rate in surge.items():
def price(fare, rate=rate):
return fare * rate
pricers[city] = price
print(pricers["Chicago"](10))
print(pricers["Chicago"](10, 3.0))
print(pricers["Chicago"].__defaults__)Output:
12.0 30.0 (1.2,)
The second call returns 30.0 because 3.0 arrives by position and fills rate. The (1.2,) in __defaults__ is untouched, so the next 1-argument call returns 12.0 again. A default works for any loop variable that a stored function reads, and a column name is fixed the same way as a multiplier.
What does this print?
def build_rules():
rules = []
for limit in [10, 20, 30]:
def check(n):
return n < limit
rules.append(check)
limit = 5
return rules
for rule in build_rules():
print(rule(8))- True 3 times, because each check kept its own limit from the loop
- False 3 times, because every check reads limit after it was set to 5
- True 3 times, because every check reads the loop's final value, 30
- NameError, because limit stops existing once the loop has finished
About this lesson
This section is part of the Functional Programming: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.