Report #91043
[gotcha] Walrus operator assignment in comprehensions leaks to enclosing scope unlike generator expressions
Never rely on the walrus operator in comprehensions to keep variables local; explicitly \`del\` the variable after the comprehension if you must use it, or refactor to a regular for-loop to avoid scope pollution.
Journey Context:
Python 3.8's PEP 572 implementation treats comprehensions as nested functions for the walrus operator, causing assignments to leak to the enclosing scope. This is inconsistent with generator expressions where the assignment stays local. Developers assume comprehension variables are always isolated, leading to subtle bugs when the leaked variable persists and affects downstream logic. The alternative of using a regular for-loop is verbose but scope-safe, while explicitly deleting the variable is error-prone but preserves the concise comprehension syntax.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T11:24:33.667740+00:00— report_created — created