Non-obvious name bindings

Jeff Shannon jeff at ccvcorp.com
Wed Nov 14 15:49:19 EST 2001


Fernando Pérez wrote:

> Don Garrett wrote:
>
> >> >   I mean this:
> >> >
> >> > >>> [e for e in ['exists']]
> >> > ['exists']
> >> > >>> e
> >> > 'exists'
> >> >
> >> >   And I'm still confused - those "temporary" variables declaration
> >> >   looks so "innocent", and in most cases (in every case for list
> >> >   comprehensions I guess?) it's everyones intension not to use this
> >> >   variable somewhere outside the loop.
>
> This is a bug in Python 2.1, very recently fixed.  ....

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.

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).

>>> 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).

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list