Skip to content

Commit

Permalink
Avoid C1901 violations within subscripts (#3517)
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Mar 17, 2023
1 parent 73df267 commit 373a77e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@ def errors():
def ok():
if x and not y:
print("x is not an empty string, but y is an empty string")


data.loc[data["a"] != ""]
data.loc[data["a"] != "", :]
8 changes: 8 additions & 0 deletions crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ pub fn compare_to_empty_string(
ops: &[Cmpop],
comparators: &[Expr],
) {
// Omit string comparison rules within subscripts. This is mostly commonly used within
// DataFrame and np.ndarray indexing.
for parent in checker.ctx.expr_ancestors() {
if matches!(parent.node, ExprKind::Subscript { .. }) {
return;
}
}

let mut first = true;
for ((lhs, rhs), op) in std::iter::once(left)
.chain(comparators.iter())
Expand Down
5 changes: 5 additions & 0 deletions crates/ruff_python_ast/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@ impl<'a> Context<'a> {
self.exprs.iter().rev().nth(2)
}

/// Return an [`Iterator`] over the current `Expr` parents.
pub fn expr_ancestors(&self) -> impl Iterator<Item = &RefEquality<'a, Expr>> {
self.exprs.iter().rev().skip(1)
}

/// Return the `Stmt` that immediately follows the current `Stmt`, if any.
pub fn current_sibling_stmt(&self) -> Option<&'a Stmt> {
self.body.get(self.body_index + 1)
Expand Down

0 comments on commit 373a77e

Please sign in to comment.