Skip to content
New issue

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

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

Already on GitHub? # to your account

B031 false positive in loop with continue/break/return #10337

Closed
MikkelSchubert opened this issue Mar 11, 2024 · 4 comments
Closed

B031 false positive in loop with continue/break/return #10337

MikkelSchubert opened this issue Mar 11, 2024 · 4 comments
Assignees
Labels
bug Something isn't working linter Related to the linter

Comments

@MikkelSchubert
Copy link

from __future__ import annotations
from itertools import groupby

def ruff_b031_false_positive(values: list[int]) -> None:
    for key, group in groupby(values):
        if key:
            list(group)
            continue # or break or return

        list(group)
$ ruff check --isolated --select B031 testcase.py
testcase.py:10:14: B031 Using the generator returned from `itertools.groupby()` more than once will do nothing on the second usage
Found 1 error.

There have been fixes for when the generator is used in different branches of an if statements, see for example #4050, but the warning still triggers if you use continue, break, or return. Tested with Ruff version 0.3.2.

@dhruvmanila
Copy link
Member

Thanks!

I think this can be solved. We would need to consider the block outside the if statement as if it's mutually exclusive with the if block if there's a continue / break / return as the last statement in the if block.

(We so need control flow graphs :))

@dhruvmanila dhruvmanila added the bug Something isn't working label Mar 11, 2024
@zanieb zanieb added the linter Related to the linter label Mar 11, 2024
@yt2b
Copy link
Contributor

yt2b commented Mar 23, 2024

@dhruvmanila
Can I try to work on this?

@dhruvmanila
Copy link
Member

@yt2b Sure! It might be a bit tricky to get it right because we don't have control flow graph and the implementation uses visitor and stack to simulate it. This comment has a visualization on what it looks like. Feel free to ping me with any questions you might have :)

@dhruvmanila
Copy link
Member

(Assigning to you but don't feel any pressure to complete it.)

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
bug Something isn't working linter Related to the linter
Projects
None yet
Development

No branches or pull requests

4 participants