Skip to content

Commit

Permalink
Treat not operations as boolean tests (#12301)
Browse files Browse the repository at this point in the history
## Summary

Closes #12285.
  • Loading branch information
charliermarsh authored Jul 12, 2024
1 parent 6febd96 commit 4e6ecb2
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
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"]

0 comments on commit 4e6ecb2

Please sign in to comment.