Odd name shadowing in comprehension

Chris Angelico rosuav at gmail.com
Sat Oct 22 23:24:44 EDT 2016


On Sun, Oct 23, 2016 at 2:14 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
>>> But it seems that the first iterator (and only that one) is evaluated
>>> in the parent context:
>>
>> Because the first iterator *can* always be evaluated.
>
> I don't understand what you mean by that. If I take you literally, it is
> obviously not true:
>
> py> [x for x in garglebarblewarble]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'garglebarblewarble' is not defined
>
> but I'm sure you know that, so I don't understand what you mean by "always".

AIUI, what he means is this:

1) Sometimes, all the iterables can be evaluated in advance.

dice_2d6 = [a+b for a in range(1,7) for b in range(1,7)]

2) But sometimes, subsequent iterables depend on the outer loop.

triangle = [a+b for a in range(1, 7) for b in range(1, a+1)]

So in case #2, you cannot evaluate the second range until you're
actually in the loop - but in both cases, the first one can be
pre-evaluated. Also, the most-outside loop's iterable gets evaluated
exactly once, whereas inner loops might be evaluated more often (or
less, for that matter).

Only in extreme edge cases involving name scoping can the evaluation
of the first iterable depend on whether it's inside or outside the
invisible function.

ChrisA



More information about the Python-list mailing list