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.partial alternative
  • nonlocal to rebind

More most-asked Python Developer questions

← All Python Developer questions