flake8-bugbear
flake8-bugbear copied to clipboard
Proposed Check: variable used outside of for-loop scope
Hi,
Python doesn't scope variables from a for loop, which I don't think I've ever intentionally used as a language feature, and has only been a source of bugs for me.
for x in range(5):
print(x)
print(x) # conspicuous usage
I think this would be the same for scopes like context managers; using the file pointer after exiting the open context manager.
I dunno if this is something that would maybe be considered for bugbear to identify.
I was thinking that when it's intentional usage could maybe be identified with something like:
x = None
for x in range(5):
print(x)
print(x)
# OR
for x in range(5):
print(x)
last_x = x #noqa
Thanks for considering this.
This would be great. One of my colleagues just found a bug in our codebase dating from 2010 that would have been caught by such a check.
Sorry I never replied here, but if a PR is done, documentation is added and unittests are added I'm inclined to accept this. Just torn if we want this on by default or optional. It's a 50/50 one I feel. I'd love more comment on this decision if anyone subscribed is around.
Some people think this is an ok thing to do. I agree it's not. Unless a variable is assigned outside the loop and then during the loop iterations the developer is explicit and assigns it to said variable etc.