Skip to content

Commit 793ff9b

Browse files
authored
Fix false positive in for mutations in return statements (B909) (#18408)
<!-- Thank you for contributing to Ruff/ty! To help us out with reviewing, please consider the following: - Does this pull request include a summary of the change? (See below.) - Does this pull request include a descriptive title? (Please prefix with `[ty]` for ty pull requests.) - Does this pull request include references to any relevant issues? --> ## Summary Fixes false positive in B909 (`loop-iterator-mutation`) where mutations inside return/break statements were incorrectly flagged as violations. The fix adds tracking for when mutations occur within return/break statements and excludes them from violation detection, as they don't cause the iteration issues B909 is designed to prevent. ## Test Plan - Added test cases covering the reported false positive scenarios to `B909.py` - Verified existing B909 tests continue to pass (no regressions) - Ran `cargo test -p ruff_linter --lib flake8_bugbear` successfully Fixes #18399
1 parent c9dff5c commit 793ff9b

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B909.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,17 @@ def func():
179179
for elem in some_list:
180180
if some_list.pop() == 2:
181181
return
182+
183+
# should not error - direct return with mutation (Issue #18399)
184+
def fail_map(mapping):
185+
for key in mapping:
186+
return mapping.pop(key)
187+
188+
def success_map(mapping):
189+
for key in mapping:
190+
ret = mapping.pop(key) # should not error
191+
return ret
192+
193+
def fail_list(seq):
194+
for val in seq:
195+
return seq.pop(4)

crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_iterator_mutation.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,6 @@ impl<'a> Visitor<'a> for LoopMutationsVisitor<'a> {
293293
if let Some(mutations) = self.mutations.get_mut(&self.branch) {
294294
mutations.clear();
295295
}
296-
visitor::walk_stmt(self, stmt);
297296
}
298297

299298
// Avoid recursion for class and function definitions.

0 commit comments

Comments
 (0)