Why is this legal?

Jeff Shannon jeff at ccvcorp.com
Wed Sep 8 17:56:11 EDT 2004


Michael George Lerner wrote:

>
>>>>f1 = Foo(); f2 = Foo()
>>>>f1.x = 'go'; f2.x = 'od'
>>>>f1.x+f2.x
>>>>        
>>>>
>'good'
>  
>
>>>>things = [f for (f,f.x) in [(f1,'bo'),(f2,'gus')]]
>>>>f1.x+f2.x
>>>>        
>>>>
>'bogus'
>  
>
>
>Is there any reason you'd ever want to do this?
>  
>

I don't know if there's a *reason* why you'd want to do this.

But note that if you rewrote the list-comp as a for loop, you'd have the 
same effect and probably not be surprised by it.  It's simply a matter 
that for loops (and list comprehensions) do not introduce a new scoping 
level in Python.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list