Skip to content

Commit

Permalink
Avoid recomending operator.itemgetter with dependence on lambda arg (#…
Browse files Browse the repository at this point in the history
…11574)

## Summary

Closes #11573.
  • Loading branch information
charliermarsh authored May 28, 2024
1 parent b36c713 commit ab107ef
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def add(x, y):
op_itemgetter = lambda x: ()
op_itemgetter = lambda x: (*x[0], x[1])
op_itemgetter = lambda x: (x[0],)
op_itemgetter = lambda x: x[x]


def op_neg3(x, y):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use anyhow::Result;

use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::{self as ast, Expr, ExprSlice, ExprSubscript, ExprTuple, Parameters, Stmt};
use ruff_python_semantic::SemanticModel;
Expand Down Expand Up @@ -221,9 +222,17 @@ fn itemgetter_op(expr: &ExprSubscript, params: &Parameters, locator: &Locator) -
let [arg] = params.args.as_slice() else {
return None;
};

// The argument to the lambda must match the subscripted value, as in: `lambda x: x[1]`.
if !is_same_expression(arg, &expr.value) {
return None;
};

// The subscripted expression can't contain references to the argument, as in: `lambda x: x[x]`.
if any_over_expr(expr.slice.as_ref(), &|expr| is_same_expression(arg, expr)) {
return None;
}

Some(Operator {
name: "itemgetter",
args: vec![subscript_slice_to_string(expr.slice.as_ref(), locator).to_string()],
Expand Down

0 comments on commit ab107ef

Please sign in to comment.