for element in container:
# some code here
temp_variable = f1(element)
# more code
# much later in the code
for element in container:
# some code
another_variable = g(temp_variable)
# more code
temp_variable = f2(element)
# more code
In the second for loop, I accidentally used variable temp_variable before it’s assigned. Normally, I’d get NameError exception, but here unfortunately it survived, valid and initialized, from the previous loop.
Are there any coding practices, IDE tools, etc., that would help prevent such bugs?
Btw, I was thinking it might be better if variables inside the loop stayed didn’t survive past the end of the loop.
EDIT
@Ignacio Vazquez-Abrams:
If I understood correctly, you suggest not to use the same variable name as a local variable in multiple loops. I have two problems with that:
-
Often the most descriptive variable name to use happens to be the same in multiple loops. Say, I used something like
unique_visitor_count. I wouldn’t want to ban this variable from being used further down in the code, in another loop. -
When working on existing code, it would be quite onerous to check if any new variable name I want to use has already been used before.
If it’s ‘much later’ in the code, then you should probably break the code up into multiple functions. It sounds like the function is too long.
Another tip is to use meaningful names.
temp_variable,tmp,temp, etc. are not good names. Use a name that describes the value that it points to. This will eliminate a large class of potential occurrences of this problem.Also, list comprehensions don’t leak their variables so if you can use them, than that’s just one more reason that they’re generally better. They are not applicable to all situations though.