Most arguments about why the design decision was made to make for-loop variables not local to the loop suggest that there are popular use cases.
The obvious use case is this:
x = default_value
for x in iterator:
# do stuff
# do something with x here
Unfortunately, often the first line is forgotten:
# should have set default value for x here
# but forgot
for x in iterator:
# do stuff
# do something with x here
So when iterator is empty, they raise NameError
if x
was not defined earlier.
This mistake gets worse with nested loops:
for y in outer_iterator:
# should have set default value for x here
# but forgot
for x in inner_iterator(y):
# do stuff
# do something with x
Here forgetting the x = default_value
results in a silent error instead of an exception if inner_iterator(y)
is empty on the second or later iteration through the outer loop.
Testing these situations is tough, because inner_iterator(y)
is not an outside argument, so unless the test is lucky enough to somehow recreate the case when it's empty, the bug won't be detected.
Are all use cases fragile or is there a safe way to rely on the scoping rule of the for-loop variables?