The late-binding loop surprise
What does this print?
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
Not [0, 1, 2]. A closure remembers the variable, not its value at the
time. Python looks up i when the function runs. By then the loop is over,
and i is 2 for every function. This is called late binding, and it is a
classic interview question and a real bug in callback code.
Two fixes:
- A default argument:
lambda i=i: i. Defaults are evaluated once, when the function is made, so each lambda captures the current value. functools.partial, or a helper function that takesias a parameter, so each closure gets its own variable.
Run it, then change the buggy list to use lambda i=i: i.