Skip to content

Fix B031 false positive for usage in mutually exclusive if/else branches#541

Open
Fridayai700 wants to merge 2 commits intoPyCQA:mainfrom
Fridayai700:fix-b031-if-else-false-positive
Open

Fix B031 false positive for usage in mutually exclusive if/else branches#541
Fridayai700 wants to merge 2 commits intoPyCQA:mainfrom
Fridayai700:fix-b031-if-else-false-positive

Conversation

@Fridayai700
Copy link

Fixes #465.

Using the groupby() generator in separate branches of an if/else is safe since only one branch executes. Previously, B031 counted all Name references in the loop body regardless of control flow, so this code was incorrectly flagged:

for _, group in itertools.groupby([]):
    if condition:
        list(group)
    else:
        list(group)  # false positive: B031

This refactors the counting logic to handle if/elif/else branches as mutually exclusive, taking the maximum usage count across branches rather than the sum. The change correctly handles:

  • Simple if/else (no flag)
  • if/elif/else chains (no flag)
  • Usage before if + inside if body (flags correctly)
  • Usage in both branches + outside (flags correctly)
  • Nested loops (always flags, as before)

Fridayai700 and others added 2 commits February 17, 2026 07:03
Using the groupby generator in separate branches of an if/else is safe
since only one branch executes. Previously, B031 counted all Name
references in the loop body regardless of control flow, flagging code
like:

    for _, group in itertools.groupby([]):
        if condition:
            list(group)
        else:
            list(group)

This refactors the counting to handle if/elif/else branches as mutually
exclusive, taking the maximum usage across branches rather than the sum.

Fixes PyCQA#465
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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

Successfully merging this pull request may close these issues.

B031 does not take into account if-else statements

1 participant