Sub topic 12
Late binding: closures created in a loop
This chapter assumes you know how closures capture names from an enclosing scope and how the LEGB lookup rule works. Both were covered in the previous chapters.
The surprise
Create three functions in a loop, each meant to return its own loop number:
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
# Output: [2, 2, 2]You might expect [0, 1, 2]. Every function returns 2 instead.
Why it happens
A closure stores a reference to the variable i. It does not store the value i had when the function was created. Python looks up the name only when the function is called. This is called late binding.
In the example above, the loop finishes before any lambda runs. At that point i holds its last value, 2. All three lambdas share the same i, so all three return 2.
The same thing happens with def inside a regular for loop:
def make_funcs():
funcs = []
for i in range(3):
def show():
return i
funcs.append(show)
return funcs
print([f() for f in make_funcs()])
# Output: [2, 2, 2]Here i belongs to make_funcs, and each show finds it through the enclosing scope. Lookup happens at call time, after the loop has ended.
Fix 1: bind the value with a default argument
Default argument values are evaluated when the function is defined. Each function therefore gets its own copy of the current i:
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])
# Output: [0, 1, 2]The parameter i is now a local name of each lambda. It is separate from the loop's i.
Fix 2: use functools.partial
functools.partial stores the argument at creation time and doesn't use a closure at all:
from functools import partial
def show(n):
return n
funcs = [partial(show, i) for i in range(3)]
print([f() for f in funcs])
# Output: [0, 1, 2]Callers can't override the value by accident, which can happen with a default argument.
Fix 3: use a factory function
A factory creates a new enclosing scope on every call, so each closure gets its own variable:
def make_show(n):
def show():
return n
return show
funcs = [make_show(i) for i in range(3)]
print([f() for f in funcs])
# Output: [0, 1, 2]Each call to make_show creates a separate n. The inner function reads that n, and nothing changes it later.
Which fix to use
| Approach | Best when | Watch out for |
|---|---|---|
| Default argument | A quick lambda in a short script | Callers can override the value |
| `functools.partial` | You are binding arguments to an existing function | The result is a `partial` object, not a plain function |
| Factory function | The closure has several lines of logic | A little more code |
Late binding is sometimes wanted
Late binding is not a defect. If a closure should see later changes to a variable, as the make_counter example did with nonlocal, the lookup-at-call-time behavior is exactly what you need. The bug appears only when you expect a snapshot and get a live reference.
Exercise
What does this code print, and how would you change it to print [10, 20, 30]? adders = [] for n in [10, 20, 30]: adders.append(lambda: n) print([f() for f in adders])
Show answer
It prints [30, 30, 30]. All three lambdas share the loop variable n, which is 30 when the loop ends. Change the lambda to lambda n=n: n, or use partial with a one-argument function, or build each lambda in a factory function. Any of these gives [10, 20, 30].