Skip to content

Commit dc322d2

Browse files
authored
[ruff] skip fix for RUF059 if dummy name is already bound (unused-unpacked-variable) (#18509)
1 parent a2de81c commit dc322d2

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

crates/ruff_linter/resources/test/fixtures/ruff/RUF059_0.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,9 @@ def f():
9494
(exponential := (exponential * base_multiplier) % 3): i + 1 for i in range(2)
9595
}
9696
return hash_map
97+
98+
99+
# see: https://github.com/astral-sh/ruff/issues/18507
100+
def f(_x):
101+
x, = "1"
102+
print(_x)

crates/ruff_linter/src/rules/ruff/rules/unused_unpacked_variable.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use ruff_python_semantic::Binding;
33
use ruff_text_size::Ranged;
44

55
use crate::checkers::ast::Checker;
6+
use crate::renamer::ShadowedKind;
67
use crate::{Edit, Fix, FixAvailability, Violation};
78

89
/// ## What it does
@@ -63,6 +64,11 @@ fn remove_unused_variable(binding: &Binding, checker: &Checker) -> Option<Fix> {
6364

6465
let name = binding.name(checker.source());
6566
let renamed = format!("_{name}");
67+
68+
if ShadowedKind::new(binding, &renamed, checker).shadows_any() {
69+
return None;
70+
}
71+
6672
if checker.settings.dummy_variable_rgx.is_match(&renamed) {
6773
let edit = Edit::range_replacement(renamed, binding.range());
6874

crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF059_RUF059_0.py.snap

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,14 @@ RUF059_0.py:86:29: RUF059 [*] Unpacked variable `that` is never used
197197
86 |+ open("") as ((this, _that)),
198198
87 87 | ):
199199
88 88 | print("hello")
200-
89 89 |
200+
89 89 |
201+
202+
RUF059_0.py:101:5: RUF059 Unpacked variable `x` is never used
203+
|
204+
99 | # see: https://github.com/astral-sh/ruff/issues/18507
205+
100 | def f(_x):
206+
101 | x, = "1"
207+
| ^ RUF059
208+
102 | print(_x)
209+
|
210+
= help: Prefix it with an underscore or any other dummy variable pattern

0 commit comments

Comments
 (0)