-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Rule B909 (loop-iterator-mutation) doesn't detect many kinds of list mutation #12164
Comments
numbers = list(range(1, 30))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers) It looks like we specifically allow this pattern... For example, we do flag an error for this: numbers = list(range(1, 30))
for i in numbers:
if i < 20:
numbers.remove(i + 1)
print(numbers) The |
I feel like we should still be flagging: numbers = list(range(1, 30))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers) But need to look at the source to understand why that exception was added. |
Ok, I think I should remove that exception -- it seems misguided. |
This was referenced Jul 17, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello and thank you for this excellent tool,
I'm running Ruff as a linter in VS Code with
select = ["ALL"]
,preview = true
and only specific rules ignored. I'm still on Python 3.7.7, and using the Ruff 2024.28.0 extension.I've found that B909 sometimes fires when I extend a list in a loop, but not when I remove or del an item from it. I'm not sure how the original Bugbear behaves in this case but in practice these seem very similar and any of them can cause bugs.
I can't find any report of this in issues, searching for "B909", "mutation", "iterator". The only issue I found was the original task to implement B038: #9511
Repros:
This does not generate any linting errors:
(from https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it-in-python)
But this triggers both B909 and PERF401:
This does not trigger B909 or PERF401 either (though it does correctly trigger FURB148 on the
enumerate
call)Same for this:
And this (don't try this one, it's an infinite loop)
The text was updated successfully, but these errors were encountered: