Scoping in Python ‘for’ loops

The likeliest answer is that it just keeps the grammar simple, hasn’t been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of assignment statements. The global keyword exists just for this reason (to signify that assignment is done at a global scope).

Update

Here’s a good discussion on the topic: http://mail.python.org/pipermail/python-ideas/2008-October/002109.html

Previous proposals to make for-loop
variables local to the loop have
stumbled on the problem of existing
code that relies on the loop variable
keeping its value after exiting the
loop, and it seems that this is
regarded as a desirable feature.

In short, you can probably blame it on the Python community 😛

Leave a Comment