for x in... x remains global

Duncan Booth duncan.booth at invalid.invalid
Wed Nov 8 07:20:54 EST 2006


Antoine De Groote <antoine at vo.lu> 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.

Blocks in Python never create new scopes. You have global variables for 
each module and one set of local variables for each function. There is a 
minor exception in that the control variables in generator expressions are 
in a separate scope, but variables are never local to a 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?

One good reason is that sometimes you want to use the loop variable after 
the end of the loop:

for x in somesequence:
   if somecondition(x):
       break
else:
   raise NotFoundError
print "found", x

Try to write lots of small functions and then you can keep the scope of 
variables suitably small.



More information about the Python-list mailing list