From a742a562fdb709c2d261ffc8e278644ed77b239d Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Sun, 20 Aug 2023 10:41:10 -0400 Subject: [PATCH] Ignore multi-comparisons in `repeated-equality-comparison-target` (#6705) Given `foo == "a" == "b" or foo == "c"`, we were suggesting `foo in {"a", "b", "c"}`. --- .../repeated_equality_comparison_target.py | 4 +++ .../repeated_equality_comparison_target.rs | 33 ++++++++++--------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/crates/ruff/resources/test/fixtures/pylint/repeated_equality_comparison_target.py b/crates/ruff/resources/test/fixtures/pylint/repeated_equality_comparison_target.py index f82e19a761..654b2c70c2 100644 --- a/crates/ruff/resources/test/fixtures/pylint/repeated_equality_comparison_target.py +++ b/crates/ruff/resources/test/fixtures/pylint/repeated_equality_comparison_target.py @@ -32,3 +32,7 @@ foo not in {"a", "b", "c"} # Uses membership test already. foo == "a" # Single comparison. foo != "a" # Single comparison. + +foo == "a" == "b" or foo == "c" # Multiple comparisons. + +foo == bar == "b" or foo == "c" # Multiple comparisons. diff --git a/crates/ruff/src/rules/pylint/rules/repeated_equality_comparison_target.rs b/crates/ruff/src/rules/pylint/rules/repeated_equality_comparison_target.rs index 37d93751e8..8d6ca59912 100644 --- a/crates/ruff/src/rules/pylint/rules/repeated_equality_comparison_target.rs +++ b/crates/ruff/src/rules/pylint/rules/repeated_equality_comparison_target.rs @@ -111,24 +111,27 @@ fn is_allowed_value(bool_op: BoolOp, value: &Expr) -> bool { return false; }; - ops.iter().all(|op| { - if match bool_op { - BoolOp::Or => !matches!(op, CmpOp::Eq), - BoolOp::And => !matches!(op, CmpOp::NotEq), - } { - return false; - } + // Ignore, e.g., `foo == bar == baz`. + let [op] = ops.as_slice() else { + return false; + }; - if left.is_call_expr() { - return false; - } + if match bool_op { + BoolOp::Or => !matches!(op, CmpOp::Eq), + BoolOp::And => !matches!(op, CmpOp::NotEq), + } { + return false; + } - if any(comparators.iter(), Expr::is_call_expr) { - return false; - } + if left.is_call_expr() { + return false; + } - true - }) + if any(comparators.iter(), Expr::is_call_expr) { + return false; + } + + true } /// Generate a string like `obj in (a, b, c)` or `obj not in (a, b, c)`.