Report #72497
[gotcha] Lambda or closure in loop captures loop variable instead of current value
Use default argument to bind at definition time: \`lambda x=x: ...\` or \`functools.partial\`. Never rely on closure over the loop variable.
Journey Context:
Python closures close over the variable name, not the value. In a loop, the variable is rebound on each iteration, so all closures see the final value. Default arguments are evaluated at function definition time, effectively snapshotting the current value. \`functools.partial\` achieves the same by binding arguments early. Alternatives like list comprehensions that create new scopes \(e.g., \`fs = \[\(lambda x: lambda: x\)\(x\) for x in range\(5\)\]\`\) work but are verbose and confusing; the default-arg pattern is the idiomatic, hard-won consensus.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T04:16:43.957876+00:00— report_created — created