Is for loop implementation a bug or feature

The for loop creates a variable and adds it to the enclosing scope. This means you can do something like

for a in range(5):


and “a” will still be persistent with the previous value assigned during iteration.
Or, you can even do something like this:

class Numbers:
   for num in range(5):


and it will print 4.

My question is, is this a bug, feature or unintended consequence of the implementation?

1 Like

Absolutely intended. Note that for isn’t limited to a bare identifier - any valid assignment-statement target can be used. For example,

>>> L = [2, 3, 5]
>>> for L[1] in range(10):
...     pass
>>> L
[2, 9, 5]

Regardless of the target of for, it follows the same rules as the same target used in an assignment statement. Unless overridden by a global or nonlocal declaration, an identifier being the target in an assignment statement (and so also in for) means it’s in the “local” scope.


in these circumstances it feels more of a (useless ?) consequence :sweat_smile:

Quite useful if you want to know when your for loop ended, e.g with enumerate

for i, value in enumerate(generator_of_values):
    if violates_assumptions(value):
        break  # now I have `i` and the value for inspection

print(f"processed {i} values")
1 Like

Unless there’s a good reason, be consistent. That’s a good design goal. Python’s rules for assignment are largely consistent (there are some exceptions - some assignment targets don’t support destructuring, for example), so all you need to learn is “this assigns to this name” and you understand the semantics. For example, you don’t need special knowledge to understand what an import statement will do inside a function; it’s exactly the same as it does outside of a function - locate the module and assign it to the corresponding name. The “assign” part takes care of everything.

def do_import():
    global math
    import math


So, there may not be anything specifically planned about for loops, but what was definitely planned was for their assignment to be the exact same thing as every other assignment.