Odd name shadowing in comprehension

eryk sun eryksun at gmail.com
Sat Oct 22 22:15:32 EDT 2016


On Sun, Oct 23, 2016 at 1:28 AM, Chris Angelico <rosuav at gmail.com> wrote:
>
> Fair enough, except that a generator expression is syntactic sugar for
> a generator function, and the return value of a generator function is
> a generator object that hasn't yet been started. So where the boundary
> is, then, is a bit of a fuzzy line.

I meant the behavior seems to have been copied to align with generator
expressions, even though the cited rationale doesn't apply. I'm not
saying this is wrong. It's useful that the expression for the outer
iterator is evaluated in the defining scope. However, it's only
documented for generator expressions, in 6.2.8. The documentation for
comprehensions in 6.2.4 makes no mention of it. Actually, it states
without qualification that a comprehension is evaluated in a separate
scope, which could be misleading:

    >>> class A:
    ...     a = [x for x in range(locals().setdefault('y', 2))]
    ...
    >>> A.y
    2



More information about the Python-list mailing list