Sub topic 9
The late-binding pitfall in loops
This chapter assumes you know how to define functions with def, how default argument values work, and how list comprehensions are written. It also builds on the previous chapter on closures. You will see why lambdas created in a loop often all return the same value, and how to fix it.
The surprise
Suppose you want a list of three functions. The first should return 0, the second 1, and the third 2. This looks reasonable:
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]You might expect [0, 1, 2]. Instead, every function returns 2.
Why it happens
A closure does not copy the value of a variable it uses. It keeps a reference to the variable itself. Python looks up the value of that variable when the function is called, not when the function is created. This is called late binding.
In the example, the loop variable i is a single variable. Each pass of the loop changes its value, and all three lambdas refer to that same i. The loop ends with i equal to 2. When you call the lambdas afterwards, each one looks up i and finds 2.
The diagram shows the order of events.
A def inside a loop behaves the same way. The problem comes from closures, not from lambda itself.
Fix 1: a default argument
Default argument values are evaluated once, when the function is created. If you write i=i, the lambda gets its own parameter named i, and the default is set to the current value of the loop variable:
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed]) # [0, 1, 2]The i on the left is the lambda's parameter. The i on the right is the loop variable, read at creation time.
This fix has a side effect. Callers can pass an argument and override the captured value, as in fixed[0](99), which returns 99. For internal use this is usually acceptable.
Fix 2: a function factory
Another fix is to create each function inside another function. Every call to the factory has its own local variable, so each closure captures a different one:
def make_returner(value):
return lambda: value
funcs = [make_returner(i) for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]Here the lambda captures value, which belongs to one call of make_returner. The loop variable no longer matters. This is the same pattern as the make_multiplier function from the previous chapter, and it does not allow callers to override the value.
Fix 3: functools.partial
functools.partial stores the current value as an argument when you create the new function, so nothing is looked up later:
from functools import partial
def show(n):
return n
funcs = [partial(show, i) for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]Choosing a fix
| Fix | Strength | Weakness |
|---|---|---|
| Default argument `i=i` | Short, stays inline | Callers can override the value |
| Factory function | Clear, no extra parameter | Needs a named helper |
| `partial` | No closure involved | Needs a named function to wrap |
Where you will meet this
The bug appears whenever you build callbacks in a loop. Examples include button handlers, validators for each field, or one function per configuration entry. If several callbacks behave as if they were all given the last item, suspect late binding.
Exercise
What does this code print, and how would you change it so it prints [10, 20, 30]? adders = [lambda: n * 10 for n in range(1, 4)] print([f() for f in adders])
Show answer
It prints [30, 30, 30], because every lambda reads the same variable n after the loop ends with n equal to 3. Capture the value at creation time with a default argument: adders = [lambda n=n: n * 10 for n in range(1, 4)]. This prints [10, 20, 30].
Exercise
Why does the factory function fix work even though the lambda inside it is still a closure?
Show answer
Each call to the factory creates a new local variable, so each lambda captures a different variable. Late binding still happens, but each variable is never changed after the call, so the lambda reads the right value.