This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ncoghlan
Recipients Damien George, emilyemorehouse, ncoghlan
Date 2019-08-05.00:15:02
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1564964102.91.0.387603674091.issue37757@roundup.psfhosted.org>
In-reply-to
Content
While implementing PEP 572, Emily noted that the check for conflicts between assignment operators and comprehension iteration variables had not yet been implemented: https://bugs.python.org/issue35224#msg334331

Damien George came across this discrepancy while implementing assignment expressions for MicroPython.

The proposed discussion regarding whether or not the PEP should be changed didn't happen, and the PEP itself misses the genuinely confusing cases where even an assignment expression that *never executes* will still make the iteration variable leak:

>>> [i for i in range(5)]
[0, 1, 2, 3, 4]
>>> [i := 10 for i in range(5)]
[10, 10, 10, 10, 10]
>>> i
10
>>> [False and (i := 10) for i in range(5)]
[False, False, False, False, False]
>>> i
4

And that side effect happens even if the assignment expression is nested further down in an inner loop:

>>> [(i, j, k) for i in range(2) for j in range(2) for k in range(2)]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> [(i, j, k) for i in range(2) for j in range(2) for k in range(2) if True or (i:=10)]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
>>> i
1

I'm at the PyCon AU sprints today, and will be working on a PR to make these cases raise TargetScopeError as specified in the PEP.
History
Date User Action Args
2019-08-05 00:15:02ncoghlansetrecipients: + ncoghlan, Damien George, emilyemorehouse
2019-08-05 00:15:02ncoghlansetmessageid: <1564964102.91.0.387603674091.issue37757@roundup.psfhosted.org>
2019-08-05 00:15:02ncoghlanlinkissue37757 messages
2019-08-05 00:15:02ncoghlancreate