Hacker News new | ask | show | jobs
by bpicolo 3743 days ago
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.
1 comments

> 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
    >>>
To be fair, generators are lazily evaluated so I would sure hope they wouldn't expose scope! That would show up in truly unique places haha