Avoid duplicate fixes for multi-import imports in RUF017 (#7063)

If a user has `import collections, functools, operator`, and we try to
import from `functools` and `operator`, we end up adding two identical
synthetic edits to preserve that import statement. We need to dedupe
them.

Closes https://github.com/astral-sh/ruff/issues/7059.
This commit is contained in:
Charlie Marsh
2023-09-02 12:58:18 +01:00
committed by GitHub
parent 71ff6f911d
commit 45680bbb44
3 changed files with 25 additions and 1 deletions

View File

@@ -12,3 +12,10 @@ sum([[1, 2, 3], [4, 5, 6]],
# OK
sum([x, y])
sum([[1, 2, 3], [4, 5, 6]])
# Regression test for: https://github.com/astral-sh/ruff/issues/7059
def func():
import functools, operator
sum([x, y], [])

View File

@@ -1,4 +1,5 @@
use anyhow::Result;
use itertools::Itertools;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
@@ -106,7 +107,7 @@ fn convert_to_reduce(iterable: &Expr, call: &ast::ExprCall, checker: &Checker) -
format!("{reduce_binding}({iadd_binding}, {iterable}, [])"),
call.range(),
),
[reduce_edit, iadd_edit],
[reduce_edit, iadd_edit].into_iter().dedup(),
))
}

View File

@@ -131,4 +131,20 @@ RUF017.py:9:1: RUF017 [*] Avoid quadratic list summation
12 13 | # OK
13 14 | sum([x, y])
RUF017.py:21:5: RUF017 [*] Avoid quadratic list summation
|
19 | import functools, operator
20 |
21 | sum([x, y], [])
| ^^^^^^^^^^^^^^^ RUF017
|
= help: Replace with `functools.reduce`
Suggested fix
18 18 | def func():
19 19 | import functools, operator
20 20 |
21 |- sum([x, y], [])
21 |+ functools.reduce(operator.iadd, [x, y], [])