Skip to content

Commit

Permalink
[flake8-simplify] Infer "unknown" truthiness for literal iterables …
Browse files Browse the repository at this point in the history
…whose items are all unpacks (`SIM222`) (astral-sh#14263)

## Summary

Resolves astral-sh#14237.

## Test Plan

`cargo nextest run` and `cargo insta test`.

---------

Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
  • Loading branch information
InSyncWithFoo and dhruvmanila authored Nov 11, 2024
1 parent f1f3bd1 commit be69f61
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,29 @@ def secondToTime(s0: int) -> ((int, int, int) or str):
print(f"{a}{''}" or "bar")
print(f"{''}{''}" or "bar")
print(f"{1}{''}" or "bar")


# Regression test for: https://github.com/astral-sh/ruff/issues/14237
for x in [*a] or [None]:
pass

for x in {*a} or [None]:
pass

for x in (*a,) or [None]:
pass

for x in {**a} or [None]:
pass

for x in [*a, *b] or [None]:
pass

for x in {*a, *b} or [None]:
pass

for x in (*a, *b) or [None]:
pass

for x in {**a, **b} or [None]:
pass
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
source: crates/ruff_linter/src/rules/flake8_simplify/mod.rs
snapshot_kind: text
---
SIM222.py:1:4: SIM222 [*] Use `True` instead of `... or True`
|
Expand Down Expand Up @@ -1060,5 +1061,5 @@ SIM222.py:168:7: SIM222 [*] Use `"bar"` instead of `... or "bar"`
168 |-print(f"{''}{''}" or "bar")
168 |+print("bar")
169 169 | print(f"{1}{''}" or "bar")


170 170 |
171 171 |
26 changes: 22 additions & 4 deletions crates/ruff_python_ast/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use crate::parenthesize::parenthesized_range;
use crate::statement_visitor::StatementVisitor;
use crate::visitor::Visitor;
use crate::{
self as ast, Arguments, CmpOp, ExceptHandler, Expr, FStringElement, MatchCase, Operator,
Pattern, Stmt, TypeParam,
self as ast, Arguments, CmpOp, DictItem, ExceptHandler, Expr, FStringElement, MatchCase,
Operator, Pattern, Stmt, TypeParam,
};
use crate::{AnyNodeRef, ExprContext};

Expand Down Expand Up @@ -1188,14 +1188,32 @@ impl Truthiness {
| Expr::Set(ast::ExprSet { elts, .. })
| Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if elts.is_empty() {
Self::Falsey
return Self::Falsey;
}

if elts.iter().all(Expr::is_starred_expr) {
// [*foo] / [*foo, *bar]
Self::Unknown
} else {
Self::Truthy
}
}
Expr::Dict(dict) => {
if dict.is_empty() {
Self::Falsey
return Self::Falsey;
}

if dict.items.iter().all(|item| {
matches!(
item,
DictItem {
key: None,
value: Expr::Name(..)
}
)
}) {
// {**foo} / {**foo, **bar}
Self::Unknown
} else {
Self::Truthy
}
Expand Down

0 comments on commit be69f61

Please sign in to comment.