-
Notifications
You must be signed in to change notification settings - Fork 2k
Use loop variables or variables defined in a loop outside the loop #20193
Description
Summary
I recently got bitten by the accidental use of a loop variable outside the loop. For example, this code works since the loop's variable name still exists after the loop is over and holds the value from the last iteration:
for x in container:
print(x)
print(x) # I can still use the value from the last iteration, which is most likely a mistake.Most of the time, code like that indicates an error or a mistake. If container is empty, for example, the loop won't run, and we'd get a NameError when trying to use the variable x. Even if we can guarantee that the loop runs and x will be valid after the loop, it's likely a logical error to use it. The same applies to other variables created inside a loop:
for x in container:
y = manipulate(x)
print(x, y)
print(y) # Likely a mistakeI tried to enable the ALL rule of ruff, but it didn't catch these mistakes. I think a rule should be added to warn about such code. It could be legitimate to use this technique to capture the last value of a loop, but in most cases, such code indicates a mistake or logical error, and it should be avoided. For the cases where this behaviour is used intentionally, the user can always ignore the rule.