Incorrect scope of list comprehension variables

Alf P. Steinbach alfps at start.no
Sun Apr 4 09:06:46 EDT 2010


* Ethan Furman:
> Steve Howell wrote:
>> On Apr 3, 9:58 pm, Tim Roberts <t... at probo.com> wrote:
>>
>>> Alain Ketterlin <al... at dpt-info.u-strasbg.fr> wrote:
>>>
>>>
>>>> I've just spent a few hours debugging code similar to this:
>>>
>>>> d = dict()
>>>> for r in [1,2,3]:
>>>>   d[r] = [r for r in [4,5,6]]
>>>> print d
>>>
>>> Yes, this has been fixed in later revisions, but I'm curious to know 
>>> what
>>> led you to believe that a list comprehension created a new scope.  I 
>>> don't
>>> that was ever promised.
>>
>>
>> Common sense about how programming languages should work?  As
>> confirmed by later revisions?
> 
> Common sense?  About *somebody else's* idea of how a programming 
> language should work?

Common sense is about practical solutions.

Since there is no practical gain from a list comprehension affecting the 
bindings of outside variables, and there correspondingly is a practical pay-off 
from list comprehensions not affecting the bindings of outside variables, common 
sense is to expect the latter.

It's in the nature of common sense that those who possess this ability often 
tend to make the same tentative assumptions when presented with the same 
problem. It doesn't mean that they're consulting each other, like your "somebody 
else's": it just means that they're applying similar common sense reasoning. So, 
there's no great conspiracy.


> Please.  Experiment and read the manual.

Common sense is applied first, as a heuristic. You really wouldn't want to drill 
down into the architect's drawings in order to get office 215 in a building. 
First you apply common sense.



Cheers & hth.,

- Alf



More information about the Python-list mailing list