Incorrect scope of list comprehension variables

Stephen Hansen apt.shansen at gmail.invalid
Mon Apr 5 02:40:19 CEST 2010


On 2010-04-04 17:01:20 -0700, Steven D'Aprano said:

> On Sun, 04 Apr 2010 05:50:01 -0700, Ethan Furman wrote:
> 
>>>> 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?
> 
> Nevertheless, it is a common intuition that the list comp variable should
> *not* be exposed outside of the list comp, and that the for-loop variable
> should. Perhaps it makes no sense, but it is very common -- I've never
> heard of anyone being surprised that the for-loop variable is exposed,
> but I've seen many people surprised by the fact that list-comps do expose
> their loop variable.

IMHO, the real confusion-point of the situation wasn't so much list 
comps vs for loops, but that list comps did expose it, but gen comps 
didn't. If one thinks about how each would most likely be implemented 
they wouldn't be surprised, but I'm glad the behavior was harmonized in 
3.x.

That said, I can't quite imagine how anyone could really sit down and 
write code which would be broken by list comps "leaking". The example 
code in this thread is just nutty. Even if list comps did create a new 
scope, why in the world would you intentionally shadow an enclosing 
iteration variable?

Obfuscation is not a good goal to go after :)

-- 
--S

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




More information about the Python-list mailing list