Sub topic 9
The late-binding pitfall in loops
This chapter assumes you can write def functions, use list comprehensions, and understand default argument values. It also assumes you have read the previous chapter on closures. You will learn why lambdas created in a loop often all return the same value, how to fix it, and how to spot the problem in code you did not write.
The symptom
Consider a list of lambdas built in a comprehension. Each one is meant to return a different number.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]You might expect [0, 1, 2]. The result is [2, 2, 2]. Nothing is wrong with range, and nothing is wrong with the lambdas. The surprise comes from when Python looks up the name i.
Why it happens
A closure does not copy the value of a variable it uses from an enclosing scope. It keeps a reference to the variable itself. Python 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 created.
In the example above, all three lambdas refer to the same variable i. The comprehension finishes before any lambda is called. At that point i holds its last value, 2. Every call therefore returns 2.
You can see the shared variable by inspecting the closure cells.
funcs = [lambda: i for i in range(3)]
print(funcs[0].__closure__[0] is funcs[1].__closure__[0]) # True
print(funcs[0].__closure__[0].cell_contents) # 2All three lambdas hold the same cell object. A cell is the small container Python uses to share a variable between a function and its enclosing scope.
The same problem with def
Lambda is not the cause. A nested def behaves the same way.
def build():
funcs = []
for i in range(3):
def show():
return i
funcs.append(show)
return funcs
print([f() for f in build()]) # [2, 2, 2]A for loop does not create a new scope for each iteration. The variable i lives in the enclosing function, and every show refers to it.
Late binding is often what you want
Late binding is a feature. It lets a closure see updates made after it was created.
def make_counter():
count = 0
def get():
return count
def bump():
nonlocal count
count += 1
return get, bump
get, bump = make_counter()
bump()
bump()
print(get()) # 2Here get and bump share count on purpose. The pitfall appears only when you wanted each function to keep its own snapshot, but the loop reuses one variable.
Fix 1: a default argument
Default argument values are evaluated once, when the function is defined. Using a default to capture the loop variable takes a snapshot at creation time.
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed]) # [0, 1, 2]The parameter i is now local to each lambda. Its default is the value that the loop variable had when that lambda was created. This is short and idiomatic, and you will see it often.
It has one weakness. The captured value becomes an ordinary parameter, so a caller can override it by accident.
print(fixed[1](99)) # 99, not 1If the function is only ever called with no arguments, this does not matter. If it is passed to code that supplies arguments, such as map or a callback API, it can cause bugs that are hard to trace. You can make the parameter keyword-only to reduce the risk. Put it after *.
safer = [lambda *, i=i: i for i in range(3)]
print([f() for f in safer]) # [0, 1, 2]Now safer[1](99) raises a TypeError, because positional arguments are rejected.
Fix 2: a factory function
A function call creates a new scope. If a helper function takes the value as a parameter and returns the inner function, each inner function closes over its own parameter.
def make_getter(value):
return lambda: value
getters = [make_getter(i) for i in range(3)]
print([g() for g in getters]) # [0, 1, 2]Each call to make_getter creates a separate variable value. This is the approach from the earlier chapter on functions that build functions, and it has no extra parameter that callers can override. It is the clearest choice when the inner function is more than a trivial expression.
Fix 3: functools.partial
functools.partial stores the argument inside a new callable object at the moment you call it. No variable is shared.
from functools import partial
def identity(x):
return x
parts = [partial(identity, i) for i in range(3)]
print([p() for p in parts]) # [0, 1, 2]This works well when you already have a named function that takes the value as a parameter. Like the default-argument fix, it lets callers add arguments, but extra positional arguments will go to identity after the stored one and raise a TypeError, so mistakes surface quickly.
Comparing the fixes
| Fix | Captures at | Strength | Weakness |
|---|---|---|---|
| Default argument `lambda i=i: ...` | Function definition | Short, no helper needed | Callers can override the value |
| Keyword-only default `lambda *, i=i: ...` | Function definition | Short, override requires a keyword | Less familiar syntax |
| Factory function | Factory call | Clear, new scope per call | Needs an extra named function |
| `functools.partial` | The `partial` call | Works with existing functions | Needs a function that accepts the value |
Where the bug hides in real code
The pitfall rarely appears in a toy example with range(3). It shows up in three common places.
- Callbacks in a loop. You register one handler per item, such as a button for each name. Every handler ends up acting on the last name.
- Dictionaries of operations. You build a table of lambdas from a list of settings, and every entry uses the last setting.
- Deferred work. You collect lambdas to run later, such as with a thread pool or a scheduler. By the time they run, the loop has finished.
Here is the second case with a fix.
rates = {"low": 0.05, "mid": 0.10, "high": 0.20}
broken = {name: (lambda price: price * rate) for name, rate in rates.items()}
print(broken["low"](100)) # 20.0, uses the last rate
working = {name: (lambda price, rate=rate: price * rate) for name, rate in rates.items()}
print(working["low"](100)) # 5.0The broken version prints 20.0 because every lambda reads the final value of rate. The working version binds rate as a default.
Edge cases to watch for
- Only the loop variable is affected, but any rebound variable counts. If you assign to a name after creating the lambda, the lambda sees the new value, even outside a loop.
- Mutable values are shared even with a snapshot. A default argument captures a reference. If the captured object is a list and you mutate it later, every function that holds it sees the change. Copy the object if you need a true snapshot.
- Variables used inside the loop body count too. Any name assigned in the loop and read in the lambda is affected, not just the loop target. Capture each one you need.
- Module-level loops behave the same way. At module level the lambda looks up a global name, and the result is the same: it reads the final value.
x = 1
show = lambda: x
x = 2
print(show()) # 2How to detect the problem
Ask one question when you write a lambda or nested function inside a loop or comprehension: does it use a variable that the loop changes? If it does and the function runs after the loop moves on, you need one of the fixes above.
A quick test is to print the results of calling all the functions after the loop ends. If they are all equal when they should differ, you have late binding. Linters often warn about this too. Pylint reports it as cell-var-from-loop, and flake8-bugbear reports it as B023.
Exercise
The code below is meant to print [0, 10, 20], but it prints [20, 20, 20]. Explain why, then fix it using a factory function.
adders = [lambda: n * 10 for n in range(3)]
print([f() for f in adders])
Show answer
Every lambda refers to the same variable n, and it is looked up when the lambda is called. After the comprehension ends, n is 2, so each call returns 2 10 = 20 ... but the output shows 20 for all three, which is the final value of `n 10`. The fix is to give each lambda its own variable:
def make(n):
return lambda: n * 10
adders = [make(n) for n in range(3)]
print([f() for f in adders]) # [0, 10, 20]
Exercise
A lambda created with lambda i=i: i is called as f(5). What does it return, and how would you prevent callers from changing the captured value?
Show answer
It returns 5, because the argument replaces the default. To prevent this, make the parameter keyword-only with lambda *, i=i: i. Then f(5) raises a TypeError, and f() still returns the captured value.
Exercise
Why does a nested def inside a for loop show the same late-binding behavior as a lambda?
Show answer
Neither a for loop nor a comprehension body creates a new scope per iteration for a def. The nested function closes over the loop variable in the enclosing scope, so it reads the variable's current value when called. Lambda and def create the same kind of closure.