ruff
a63ad975 - [`pylint`] Avoid false positives in `else` clause (`PLR1733`) (#25177)

Commit
116 days ago
[`pylint`] Avoid false positives in `else` clause (`PLR1733`) (#25177) ## Summary The `PLR1733` (unnecessary-dict-index-lookup) rule was incorrectly firing on dictionary accesses inside the `else` clause of a `for` loop. The `else` clause has different control-flow semantics — it only executes when the loop completes without `break` — and iteration variables from inner loops may not be in scope or may have stale values. ## Root cause In `unnecessary_dict_index_lookup()`, the `stmt_for.orelse` was being visited along with `stmt_for.body`: ```rust visitor.visit_body(&stmt_for.body); visitor.visit_body(&stmt_for.orelse); // <-- this was the bug ``` The `else` clause of a `for` loop is not part of the iteration context. Variables bound in the outer loop may be unbound if the loop body never ran, or stale from the last iteration if the loop completed. ## Fix Remove the `visitor.visit_body(&stmt_for.orelse)` call so the `else` clause is not checked for unnecessary dict lookups. ## Validation ```bash # False positive case (now correctly passes) cargo run -p ruff -- check test.py --isolated --select PLR1733 --preview # Before: 1 error (PLR1733 false positive) # After: All checks passed # Existing cases still work cargo test -p ruff_linter unnecessary_dict_index # PASS # Zulip pattern is still detected correctly cargo run -p ruff -- check test_zulip.py --isolated --select PLR1733 --preview # Correctly detects: mapped_arrays[mapped_label][i] += value_arrays[label][i] ``` ## Before `ruff check` would report a false positive on `result[res_glob]` inside the `else` clause of the outer `for` loop, and the autofix would suggest `res_priority` which is incorrect (the inner loop variable may be unbound/stale). ## After `ruff check` correctly skips the `else` clause of the `for` loop — no false positive. Fixes #25150 --------- Co-authored-by: Aniket Karne <aniketkarne@gmail.com> Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
Author
Parents
Loading