Scoping in Python ‘for’ loops

I’m not asking about Python’s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended):

for foo in xrange(10):
    bar = 2
print(foo, bar)

The above will print (9,2).

This strikes me as weird: ‘foo’ is really just controlling the loop, and ‘bar’ was defined inside the loop. I can understand why it might be necessary for ‘bar’ to be accessible outside the loop (otherwise, for loops would have very limited functionality). What I don’t understand is why it is necessary for the control variable to remain in scope after the loop exits. In my experience, it simply clutters the global namespace and makes it harder to track down errors that would be caught by interpreters in other languages.

7 Answers
7

Leave a Comment