Skip to content

[pycodestyle] Auto-fix redundant boolean comparison (E712) #17090

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Apr 23, 2025
Merged
29 changes: 29 additions & 0 deletions crates/ruff_python_ast/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1355,6 +1355,24 @@ fn is_empty_f_string(expr: &ast::ExprFString) -> bool {
})
}

fn is_redundant_boolean_comparison(op: CmpOp, comparator: &Expr) -> (bool, bool) {
match op {
CmpOp::Is => {
if let Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) = comparator {
return (true, *value);
}
(false, false)
}
CmpOp::IsNot => {
if let Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) = comparator {
return (true, !*value);
}
(false, false)
}
_ => (false, false),
}
}

pub fn generate_comparison(
left: &Expr,
ops: &[CmpOp],
Expand All @@ -1373,6 +1391,17 @@ pub fn generate_comparison(
.unwrap_or(left.range())],
);

if ops.len() == 1 {
let (op, comparator) = (ops[0], &comparators[0]);
if let (true, kind) = is_redundant_boolean_comparison(op, comparator) {
return if kind {
contents
} else {
format!("not {contents}")
};
}
}

for (op, comparator) in ops.iter().zip(comparators) {
// Add the operator.
contents.push_str(match op {
Expand Down
Loading