Odd name shadowing in comprehension

Chris Angelico rosuav at gmail.com
Sat Oct 22 21:26:08 EDT 2016


On Sun, Oct 23, 2016 at 11:43 AM, Terry Reedy <tjreedy at udel.edu> wrote:
>> Normally, a comprehension is described as being equivalent to an
>> unrolled loop, inside a nested function. That would be like this:
>>
>> def temp():
>>     ret = []
>>     for x in range(y):
>>         for y in range(3):
>>             ret.append((x,y))
>>     return ret
>> temp()
>
>
> This would make the first example fail, which would not be nice.
>

Actually, I discovered this while trying to prove that order of the
loops in a comprehension was an easily-detected problem - that if you
got them wrong, you'd get a quick UnboundLocalError. While this is
true if you have three loops, it's NOT true of the one that's
evaluated first. (This in relation to the python-ideas thread about
wanting to be able to switch the order. Why bother, if getting it
wrong gives instant feedback?)

It's a bit of an edge case, as created by the nested function. Lambda
functions don't have this issue, because they can't assign to anything
other than the parameters (which are up front); genexp and
comprehension functions, however, have internal assignments caused by
the 'for' loops. As such, it's possible to trigger UnboundLocalError -
*except* in that very first loop iterable, which is now evaluated as a
parameter.

Needs to be documented somewhere, methinks.

ChrisA



More information about the Python-list mailing list