Skip to content

Commit

Permalink
Preserve parentheses in quadratic-list-summation (#7719)
Browse files Browse the repository at this point in the history
Closes #7718.
  • Loading branch information
charliermarsh committed Sep 29, 2023
1 parent b528006 commit e9f8b91
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
5 changes: 5 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF017.py
Expand Up @@ -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), [])
Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand Down
Expand Up @@ -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), [])


0 comments on commit e9f8b91

Please sign in to comment.