Skip to content
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

Treat not operations as boolean tests #12301

Merged
merged 1 commit into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF019.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
if k in d and d[(k)]:
pass

not ("key" in dct and dct["key"])

bool("key" in dct and dct["key"])

# OK
v = "k" in d and d["k"]

Expand Down
7 changes: 7 additions & 0 deletions crates/ruff_linter/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1140,6 +1140,13 @@ impl<'a> Visitor<'a> for Checker<'a> {
self.visit_expr(body);
self.visit_expr(orelse);
}
Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::Not,
operand,
range: _,
}) => {
self.visit_boolean_test(operand);
}
Expr::Call(ast::ExprCall {
func,
arguments,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,46 @@ RUF019.py:13:4: RUF019 [*] Unnecessary key check before dictionary access
13 |+if d.get((k)):
14 14 | pass
15 15 |
16 16 | # OK
16 16 | not ("key" in dct and dct["key"])

RUF019.py:16:6: RUF019 [*] Unnecessary key check before dictionary access
|
14 | pass
15 |
16 | not ("key" in dct and dct["key"])
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUF019
17 |
18 | bool("key" in dct and dct["key"])
|
= help: Replace with `dict.get`

ℹ Safe fix
13 13 | if k in d and d[(k)]:
14 14 | pass
15 15 |
16 |-not ("key" in dct and dct["key"])
16 |+not (dct.get("key"))
17 17 |
18 18 | bool("key" in dct and dct["key"])
19 19 |

RUF019.py:18:6: RUF019 [*] Unnecessary key check before dictionary access
|
16 | not ("key" in dct and dct["key"])
17 |
18 | bool("key" in dct and dct["key"])
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUF019
19 |
20 | # OK
|
= help: Replace with `dict.get`

ℹ Safe fix
15 15 |
16 16 | not ("key" in dct and dct["key"])
17 17 |
18 |-bool("key" in dct and dct["key"])
18 |+bool(dct.get("key"))
19 19 |
20 20 | # OK
21 21 | v = "k" in d and d["k"]
Loading