Non-obvious name bindings

Fernando Pérez fperez at pizero.colorado.edu
Wed Nov 14 17:03:46 EST 2001


On Wed, 14 Nov 2001, Jeff Shannon wrote:

> If I'm reading the bug report right, then it *is* expected behavior that list
> comp variables are function-local variables, not true "temporary" variables.

You are right. The problem is that the list comp. index was propagating
*outside* of a function magically. After using a list comprehension your
global namespace would grow variables all by itself. Very disconcerting.

> 
> C++ (IIRC) treats loop indices as being limited to the scope of the loop only,
> and invalid once the loop ends.  Python, however, has a much simpler scoping
> scheme, and doesn't use a separate scope for loops (and list comps are just
> syntax sugar for a for-loop).
> 

C++ treats variables as *block* local:

for(int i=0;i<n;i++) {...
// i exists here
} 
// i doesn't exist anymore (declared in above block header)

but:
int i;
for(int i=0;i<n;i++) {...
// i exists
}
// i still exists (declare outside of block header

I hope I'm not crossing wires here, I haven't written C++ in a while.

> >>> def Example(mystring):
> ...  spam = [char for char in mystring]
> ...  print char
> ...
> >>> Example('spam and eggs')
> s
> >>> char
> Traceback (innermost last):
>   File "<interactive input>", line 1, in ?
> NameError: There is no variable named 'char'
> >>>
> 
> This is the expected behavior.  There is nothing about list comprehensions that
> limits their variables to *only* within the list comp, just as with for-loops.
> The bug reported on SF would (I think) have made char a global variable, thus
> there would've been no NameError (I'm actually using 2.0 not 2.1 for this, so
> can't demonstrate the buggy behavior).

The bug appears if you do the above in a file, not at the interpreter. Don't
know why the difference. Try my original post which had example code, copy it
to a file and run it, you should see the problem (if it exists in 2.0).

Cheers,

f.




More information about the Python-list mailing list