Python Developer interview question · Most asked
What is the late-binding closure gotcha in Python?
Summary
Closures capture variables, not values: lambdas created in a loop all see the variable's final value when called. Fix it by binding the current value as a default argument or using functools.partial.
Longer Answer
nonlocal lets inner functions rebind outer variables. This gotcha often appears in callback registration and list comprehensions creating lambdas.
Code Example
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
Key Points
- Closures look up variables at call time
- Default args capture current values
functools.partialalternativenonlocalto rebind
More most-asked Python Developer questions
- Backend Python interview: explain N+1 queries.
- Backend Python interview: explain authN vs authZ.
- Backend Python interview: explain SQL injection prevention.
- Explain decorators in Python.
- Explain context managers in Python.
- Explain GIL in Python.
- Explain threading vs multiprocessing vs asyncio in Python.
- Explain generators in Python.