Full answer
python
from functools import partial
handlers = []
for name in ["save", "load", "quit"]:
handlers.append(lambda: f"clicked {name}")
print([h() for h in handlers])
fixed = [lambda name=name: f"clicked {name}" for name in ["save", "load", "quit"]]
print([h() for h in fixed])
def make_handler(name):
return lambda: f"clicked {name}"
print([make_handler(n)() for n in ["save", "load"]])
print([partial(str.format, "clicked {}", n)() for n in ["save", "load"]])Output:
text
['clicked quit', 'clicked quit', 'clicked quit']
['clicked save', 'clicked load', 'clicked quit']
['clicked save', 'clicked load']
['clicked save', 'clicked load']All three buttons report 'quit' because each lambda refers to the same variable name, which ends the loop as 'quit'. The default-argument version evaluates name when each lambda is defined. A factory function creates a new scope per call, so each closure gets its own name. partial stores the argument value directly. This bug appears in GUI callbacks, scheduled tasks and dictionaries of handlers.
python
from functools import partial
handlers = []
for name in ["save", "load", "quit"]:
handlers.append(lambda: f"clicked {name}")
print([h() for h in handlers])
fixed = [lambda name=name: f"clicked {name}" for name in ["save", "load", "quit"]]
print([h() for h in fixed])
def make_handler(name):
return lambda: f"clicked {name}"
print([make_handler(n)() for n in ["save", "load"]])
print([partial(str.format, "clicked {}", n)() for n in ["save", "load"]])Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Closures bind variables, not values
- Lookup happens at call time
- Default arguments capture values
- Factory functions create new scopes
- partial stores arguments
Common mistakes
- Creating callbacks in loops without binding
- Assuming each iteration gets a new variable
Follow-ups
- How does this differ in JavaScript with let?
- Can the default-argument fix be misused by callers?
Tips
- Explain call-time lookup