Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new rule - enforce that loop variables are not used outside the loop #13742

Closed
DetachHead opened this issue Oct 14, 2024 · 5 comments
Closed

Comments

@DetachHead
Copy link

DetachHead commented Oct 14, 2024

the fact that loop variables are still in scope outside of the loop is a very common source of bugs:

for val in values:
    print(val)

... # several lines later

value = 1
print(val) # it's very likely the user intended to use value instead of val

i know there are cases where this is intentional, for example:

for value in values:
    ...
print(f"the last value was {value}")

but imo it's a bad idea to rely on this functionality. what if values was empty? value will be undefined which will cause a runtime error.

in most other languages, loop variables are only in scope within the loop, which is much less error-prone. it would be nice if there was a rule that enforced this:

for val in values:
    ...
print(val) # error: loop variable used outside of loop
@KotlinIsland
Copy link
Contributor

what if values was empty?

you would get an error in bpr

@KotlinIsland

This comment was marked as outdated.

@DetachHead DetachHead changed the title new rule - enforce that loop variables are deleted at the end of the loop new rule - enforce that loop variables are not used outside the loop Oct 14, 2024
@KotlinIsland
Copy link
Contributor

could this also apply to if statements with walrus:

if match := re.search(...):
  print(match)
print(match)  # error, don't do that

@diceroll123
Copy link
Contributor

This would be Pylint's W0631, which at this time is marked as not implemented in Ruff, in #970

https://pylint.readthedocs.io/en/stable/user_guide/messages/warning/undefined-loop-variable.html

@DetachHead
Copy link
Author

oh right, closing in favor of #970

@DetachHead DetachHead closed this as not planned Won't fix, can't repro, duplicate, stale Oct 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants