Skip to content

Commit

Permalink
Avoid duplicate fixes for multi-import imports in RUF017 (#7063)
Browse files Browse the repository at this point in the history
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 #7059.
  • Loading branch information
charliermarsh committed Sep 2, 2023
1 parent 71ff6f9 commit 45680bb
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
7 changes: 7 additions & 0 deletions crates/ruff/resources/test/fixtures/ruff/RUF017.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,10 @@
# 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], [])
3 changes: 2 additions & 1 deletion crates/ruff/src/rules/ruff/rules/quadratic_list_summation.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use anyhow::Result;
use itertools::Itertools;

use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
Expand Down Expand Up @@ -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(),
))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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], [])


0 comments on commit 45680bb

Please sign in to comment.