Re:Comprehensions in Python the Jedi way
by bpicolo on Sunday March 27, 2016 @11:30AM
(#11370265)
Pretty sure it was a bug that they kept for backwards compat, not intentional, though I may be wrong. Py3 let them shed it off though.
[ Parent
| on HN ]
> Pretty sure it was a bug that they kept for backwards compat, not intentional
Yep, as demonstrated by only list comprehensions exposing this behaviour (on python 2) whereas none of generator comprehensions, dictionary comprehensions or set comprehensions do:
>>> [x for x in range(5)]
[0, 1, 2, 3, 4]
>>> x
4
>>> {y for y in range(5)}
set([0, 1, 2, 3, 4])
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> {y:y for y in range(5)}
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> list(y for y in range(5))
[0, 1, 2, 3, 4]
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>>