mirror of
https://github.com/astral-sh/ruff.git
synced 2025-10-01 14:21:24 +00:00
Preserve parentheses in quadratic-list-summation
(#7719)
Closes https://github.com/astral-sh/ruff/issues/7718.
This commit is contained in:
parent
b5280061f8
commit
e9f8b91eb5
3 changed files with 41 additions and 1 deletions
|
@ -19,3 +19,8 @@ def func():
|
|||
import functools, operator
|
||||
|
||||
sum([x, y], [])
|
||||
|
||||
|
||||
# Regression test for: https://github.com/astral-sh/ruff/issues/7718
|
||||
def func():
|
||||
sum((factor.dims for factor in bases), [])
|
||||
|
|
|
@ -3,6 +3,8 @@ use itertools::Itertools;
|
|||
|
||||
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
|
||||
use ruff_macros::{derive_message_formats, violation};
|
||||
use ruff_python_ast::node::AstNode;
|
||||
use ruff_python_ast::parenthesize::parenthesized_range;
|
||||
use ruff_python_ast::{self as ast, Arguments, Expr};
|
||||
use ruff_python_semantic::SemanticModel;
|
||||
use ruff_text_size::Ranged;
|
||||
|
@ -100,7 +102,15 @@ fn convert_to_reduce(iterable: &Expr, call: &ast::ExprCall, checker: &Checker) -
|
|||
checker.semantic(),
|
||||
)?;
|
||||
|
||||
let iterable = checker.locator().slice(iterable);
|
||||
let iterable = checker.locator().slice(
|
||||
parenthesized_range(
|
||||
iterable.into(),
|
||||
call.arguments.as_any_node_ref(),
|
||||
checker.indexer().comment_ranges(),
|
||||
checker.locator().contents(),
|
||||
)
|
||||
.unwrap_or(iterable.range()),
|
||||
);
|
||||
|
||||
Ok(Fix::suggested_edits(
|
||||
Edit::range_replacement(
|
||||
|
|
|
@ -146,5 +146,30 @@ RUF017.py:21:5: RUF017 [*] Avoid quadratic list summation
|
|||
20 20 |
|
||||
21 |- sum([x, y], [])
|
||||
21 |+ functools.reduce(operator.iadd, [x, y], [])
|
||||
22 22 |
|
||||
23 23 |
|
||||
24 24 | # Regression test for: https://github.com/astral-sh/ruff/issues/7718
|
||||
|
||||
RUF017.py:26:5: RUF017 [*] Avoid quadratic list summation
|
||||
|
|
||||
24 | # Regression test for: https://github.com/astral-sh/ruff/issues/7718
|
||||
25 | def func():
|
||||
26 | sum((factor.dims for factor in bases), [])
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUF017
|
||||
|
|
||||
= help: Replace with `functools.reduce`
|
||||
|
||||
ℹ Suggested fix
|
||||
1 |+import functools
|
||||
2 |+import operator
|
||||
1 3 | x = [1, 2, 3]
|
||||
2 4 | y = [4, 5, 6]
|
||||
3 5 |
|
||||
--------------------------------------------------------------------------------
|
||||
23 25 |
|
||||
24 26 | # Regression test for: https://github.com/astral-sh/ruff/issues/7718
|
||||
25 27 | def func():
|
||||
26 |- sum((factor.dims for factor in bases), [])
|
||||
28 |+ functools.reduce(operator.iadd, (factor.dims for factor in bases), [])
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue