Incorrect scope of list comprehension variables

Stephen Hansen apt.shansen at gmail.invalid
Sun Apr 4 20:42:08 EDT 2010


On 2010-04-04 14:50:54 -0700, Paul Rubin said:

> Alain Ketterlin <alain at dpt-info.u-strasbg.fr> writes:
>> d[r] = [r for r in [4,5,6]]
>> THe problem is that the "r" in d[r] somehow captures the value of the
>> "r" in the list comprehension, and somehow kills the loop interator.
> 
> Yes, this is a well known design error in Python 2.x.  The 3.x series
> fixes this error but introduces other errors of its own.  It is evil
> enough that I almost always use this syntax instead:
> 
>     d[r] = list(r for r in [4,5,6])
> 
> that works in 3.x and the later releases of 2.x.  In early 2.x (maybe up
> to 2.2) it throws an error at compile time rather than at run time.


I have a dramatic suggestion.

Why not use this syntax:

d[r] = [something_else for something_else in [4,5,6]]

Where something_else is basically any conceivable name in the whole 
wide world which does not have meaning in the current local scope.

Just for clarity's sake, not sharing names is swell.

-- 
--S

... p.s: change the ".invalid" to ".com" in email address to reply privately.




More information about the Python-list mailing list