Sub topic 12
Late binding: closures created in a loop
This chapter assumes you know how to define and call functions, how the LEGB lookup rule orders local, enclosing, global, and built-in names, and how closures capture names from an enclosing scope. It builds on the enclosing-scope and nonlocal chapters. Here the focus is one common bug: closures created in a loop that all see the same final value.
The surprise
Start with a loop that builds a list of small functions. Each function is meant to return the loop number it was created with.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
# Output: [2, 2, 2]You might expect [0, 1, 2]. The result is [2, 2, 2]. Nothing is wrong with range or with the list comprehension. The cause is how a closure finds the value of a name it did not define itself.
What "late binding" means
A closure does not copy the value of an outer variable when the function is created. It keeps a reference to the variable itself, and it looks up the variable's current value each time the function runs. This is called late binding: the name is resolved when the function is called, not when it is defined.
This is the same lookup you already know. When lambda: i runs, Python searches for i using LEGB. i is not local to the lambda, so Python moves outward and finds it in the enclosing scope. It reads whatever object i refers to at that moment.
In the example above, all three lambdas share one i. Python creates the lambdas during the loop, but it does not call them until afterward. By then the loop is finished and i is bound to 2. Every call reads 2.
The same thing happens with a regular def inside a loop.
def build():
funcs = []
for n in range(3):
def show():
return n
funcs.append(show)
return funcs
print([f() for f in build()])
# Output: [2, 2, 2]Here the loop variable n lives in the local scope of build. Each show function refers to that one variable in build's scope. The loop rebinds n on each pass, so after the loop n refers to 2.
One variable, many closures
The diagram below shows why the closures agree. There is one variable, and each function holds a reference to the variable, not to a number.
You can see the shared variable directly if you rebind it later.
funcs = [lambda: i for i in range(3)]
print(funcs[0]())
# Output: 2Note that in Python 3 the variable i of a list comprehension lives in the comprehension's own scope, and the lambdas capture that scope's i. The behavior is the same either way: one variable, shared by every closure from that loop.
Proving that the lookup is late
A smaller example shows the timing without any loop. The function reads message when it is called, so changing the variable after definition changes the result.
def make_greeter():
message = "hello"
def greet():
return message
message = "goodbye"
return greet
print(make_greeter()())
# Output: goodbyegreet was defined while message was "hello", but it returns "goodbye". The function never stored "hello". It stored a link to the name message in make_greeter's scope.
Fix 1: bind the value with a default argument
Default argument values are evaluated once, at the moment the function is defined. You can use that to capture the current value of the loop variable.
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])
# Output: [0, 1, 2]In lambda i=i: i, the right-hand i is evaluated when the lambda is created, so it reads the current loop value. That value becomes the default for the lambda's own parameter i. Inside the lambda, i is now a local name (a parameter), so no outer lookup happens at call time.
This works with def too.
def build():
funcs = []
for n in range(3):
def show(n=n):
return n
funcs.append(show)
return funcs
print([f() for f in build()])
# Output: [0, 1, 2]The drawback is that the function now accepts an extra argument. Someone can call f(99) and override the captured value. If that is a risk, use one of the next two fixes.
Fix 2: create a new scope with a factory function
Each call to a function creates a fresh local scope. If a helper function builds the closure, each closure gets its own enclosing variable.
def make_returner(value):
def returner():
return value
return returner
funcs = [make_returner(i) for i in range(3)]
print([f() for f in funcs])
# Output: [0, 1, 2]Each call to make_returner creates a new value variable, bound to the number passed in. The three closures point at three separate variables. The inner function takes no extra parameters, so callers cannot override the value.
Fix 3: use functools.partial
functools.partial stores the argument inside a new callable object when you create it. No scope lookup is involved at call time.
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]partial(show, i) evaluates i immediately and keeps the resulting object. This is often the clearest option when you already have a named function that takes the value as a parameter.
Choosing between the fixes
| Fix | How it captures the value | Extra argument visible to callers | Best when |
|---|---|---|---|
| Default argument | At definition time, through the default | Yes | A quick lambda or short callback |
| Factory function | Each call creates a new enclosing scope | No | You want a clean signature and may need several captured values |
| `functools.partial` | Stored in the partial object | No | The target is already a named function |
Where this bug shows up in practice
The loop-and-lambda pattern appears in more places than list comprehensions.
- Callbacks for GUI buttons, where each button should report its own index.
- Event handlers or hooks registered in a loop.
- Tasks submitted to a thread pool or scheduler inside a loop, when the task is a closure.
- Validators or filters built from a list of configuration values.
Here is a realistic case: building a dictionary of operations from a list of multipliers.
multipliers = [2, 3, 4]
ops = {}
for m in multipliers:
ops[m] = lambda x: x * m
print(ops[2](10))
# Output: 40The key 2 suggests that ops[2] multiplies by 2, so you would expect 20. Every lambda reads m, which is 4 after the loop, so the result is 40. The fix is the same: write lambda x, m=m: x * m, or build each function with a factory.
multipliers = [2, 3, 4]
ops = {}
for m in multipliers:
ops[m] = lambda x, m=m: x * m
print(ops[2](10))
# Output: 20Edge cases
Late binding only matters when the captured variable is rebound after the closure is created. Several situations are safe.
- The closure runs before the next iteration. If you call the function inside the loop body, the variable still has the right value at that moment.
- The captured name is never rebound. A closure over a constant, or over a variable assigned once, behaves as expected.
- The captured object is mutated, not rebound. The closure sees the mutation, because it holds the variable and the variable points at the same object. This is the mutation-versus-rebinding distinction from earlier chapters, and late binding can make it surprising.
def make_reader():
data = [1]
def read():
return list(data)
data.append(2)
return read
print(make_reader()())
# Output: [1, 2]Late binding is not a defect. It is what lets a closure share state with its enclosing function and see later updates, as in the counter that uses nonlocal. The bug appears only when you expected a snapshot and got a live reference.
Common errors
- Assuming a lambda snapshots the loop value. Lambdas and
deffunctions behave the same way. Neither copies the value at creation. - Fixing with
lambda: iand a different loop name. Renaming the loop variable does not change anything. The closure still holds a variable, not a value. - Adding the default argument but forgetting the right-hand side.
lambda i: imakesia required parameter and does not capture anything. You needlambda i=i: i. - Using
globalornonlocalas a fix. These statements change which variable is rebound. They do not turn a live reference into a snapshot. - Expecting a generator expression to behave differently. A generator expression is lazy, so it evaluates later and sees the final value if the loop variable is outer and has since changed.
values = [1, 2, 3]
total = 10
gen = (v + total for v in values)
total = 100
print(list(gen))
# Output: [101, 102, 103]Here the outermost iterable values is evaluated immediately, but total is looked up when the generator is consumed. This is late binding again.
Exercises
Exercise
What does this code print, and why? adders = [] for n in range(3): adders.append(lambda x: x + n) print([f(10) for f in adders])
Show answer
It prints [12, 12, 12]. Each lambda refers to the single variable n, not to the value it had when the lambda was created. When the lambdas are called after the loop, n is 2, so every call returns x + 2.
Exercise
Rewrite the code from the previous exercise so that it prints [10, 11, 12]. Give two different ways.
Show answer
Default argument: adders.append(lambda x, n=n: x + n). Factory function: define makeadder(n) that returns an inner function lambda x: x + n, then use adders.append(makeadder(n)). Both capture the current value of n when each function is created. functools.partial with a two-argument helper, such as partial(add, n) where add(n, x) returns n + x, also works.
Exercise
Why does lambda i: i not fix the loop bug, while lambda i=i: i does?
Show answer
In lambda i: i, the name i is a required parameter, so the lambda captures nothing and must be called with an argument. In lambda i=i: i, the default value is evaluated when the lambda is created, so it stores the current loop value, and inside the lambda i is a local parameter that needs no outer lookup.