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

Rule to detect changes to iterable object of loop #445

Closed
mimre25 opened this issue Jan 10, 2024 · 5 comments
Closed

Rule to detect changes to iterable object of loop #445

mimre25 opened this issue Jan 10, 2024 · 5 comments

Comments

@mimre25
Copy link
Contributor

mimre25 commented Jan 10, 2024

Recently I've ran into a classic bug in a code base, to illustrate a minimal example:

some_list = [1,2,3]
for i in some_list:
  if i % 2 == 0:
    some_list.remove(i)
  print(i)

To nobodies surprise this prints only 1 and 2.

I was surprised that none of my linters caught this.

Anyway, would it be possible to add a rule that detects changes to the iterable that is being iterated?

I'm also more than happy to contribute 🙂

@mimre25 mimre25 changed the title Rule to detect changes to iterator of loop Rule to detect changes to iterable object of loop Jan 10, 2024
@cooperlees
Copy link
Collaborator

Yeah, I think we've all been here.

This sounds good, but I think in general we should just detect if it is a mutable iterable when we see remove in a loop and suggest saving the indexs and then removing them in reverse? Or am I missing something here?

Anyways, in general this sounds good. Feel free to make a POC diff and we can comment on there.

@mimre25
Copy link
Contributor Author

mimre25 commented Jan 12, 2024

I've went with an approach that alerts for any mutations of the loop iterator (eg .remove or del).

PR is in #446

@mimre25
Copy link
Contributor Author

mimre25 commented Jan 15, 2024

FYI: While starting to implement this rule into ruff yesterday I might have found a bug in my initial implementation.

@cooperlees please hold off the release until I verify my suspicion and fix it ~ I'll check this out later today.

@mimre25
Copy link
Contributor Author

mimre25 commented Jan 15, 2024

Ok, I was seeing something, but that code wasn't used - I've opened #488 to remove it, to avoid future bugs 🙂

@cooperlees
Copy link
Collaborator

This is released and we have dedicated improvements issue. So let's move there.

I yanked 24.1.15 + 24.1.15 due to bugs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants