for x in... x remains global

Diez B. Roggisch deets at nospam.web.de
Wed Nov 8 07:09:31 EST 2006


Antoine De Groote wrote:

> for x in range(3): pass
> 
> After this statement is executed x is global variable. This seems very
> unnatural to me and caused me 3 three days of debugging because I was
> unintentionally using x further down in my program (typo). I would have
> thought that variables like this are local to the for block.
> 
> Is there a reason this is not the case? Maybe there are PEPs or
> something else about the matter that you can point me to?

It's an somewhat unfortunate fact that loop variables leak to the outer
scope.  List-comps as well, btw.

In 

http://www.python.org/dev/peps/pep-0289/

it says that this will be remedied in Py3K 

"""
List comprehensions also "leak" their loop variable into the surrounding
scope. This will also change in Python 3.0, so that the semantic definition
of a list comprehension in Python 3.0 will be equivalent to list(<generator
expression>). Python 2.4 and beyond should issue a deprecation warning if a
list comprehension's loop variable has the same name as a variable used in
the immediately surrounding scope.
"""

And while I can't make an authorative statement about this, I can imagine
that it won't be fixed anywhere in python2.X, as code like this is
certainly to be found:

for x in some_xes:
    if condition(x):
        break

print x


Diez



More information about the Python-list mailing list