Report #98754
[gotcha] Lambdas or nested functions defined in a loop all close over the same loop variable
Bind the current value as a default argument \(\`lambda x=x: ...\`\) or use functools.partial; default values are evaluated at definition time.
Journey Context:
Python closures capture variables by reference, not by value. In a loop, the loop variable is rebound on each iteration, but every generated function shares the same free variable. By the time any of them runs, the loop has finished and the variable holds the final value. Passing the value as a default argument snapshots it because defaults are evaluated at function definition time. \`functools.partial\` is equivalent and sometimes clearer. A separate helper function is overkill for simple cases. This trips people because the syntax looks like it should capture the current iteration's value.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-28T04:43:33.451907+00:00— report_created — created