Skip to content

Commit 4e6ecb2

Browse files
Treat not operations as boolean tests (#12301)
## Summary Closes #12285.
1 parent 6febd96 commit 4e6ecb2

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

crates/ruff_linter/resources/test/fixtures/ruff/RUF019.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@
1313
if k in d and d[(k)]:
1414
pass
1515

16+
not ("key" in dct and dct["key"])
17+
18+
bool("key" in dct and dct["key"])
19+
1620
# OK
1721
v = "k" in d and d["k"]
1822

crates/ruff_linter/src/checkers/ast/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1140,6 +1140,13 @@ impl<'a> Visitor<'a> for Checker<'a> {
11401140
self.visit_expr(body);
11411141
self.visit_expr(orelse);
11421142
}
1143+
Expr::UnaryOp(ast::ExprUnaryOp {
1144+
op: UnaryOp::Not,
1145+
operand,
1146+
range: _,
1147+
}) => {
1148+
self.visit_boolean_test(operand);
1149+
}
11431150
Expr::Call(ast::ExprCall {
11441151
func,
11451152
arguments,

crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF019_RUF019.py.snap

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,46 @@ RUF019.py:13:4: RUF019 [*] Unnecessary key check before dictionary access
7777
13 |+if d.get((k)):
7878
14 14 | pass
7979
15 15 |
80-
16 16 | # OK
80+
16 16 | not ("key" in dct and dct["key"])
8181

82+
RUF019.py:16:6: RUF019 [*] Unnecessary key check before dictionary access
83+
|
84+
14 | pass
85+
15 |
86+
16 | not ("key" in dct and dct["key"])
87+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUF019
88+
17 |
89+
18 | bool("key" in dct and dct["key"])
90+
|
91+
= help: Replace with `dict.get`
8292

93+
Safe fix
94+
13 13 | if k in d and d[(k)]:
95+
14 14 | pass
96+
15 15 |
97+
16 |-not ("key" in dct and dct["key"])
98+
16 |+not (dct.get("key"))
99+
17 17 |
100+
18 18 | bool("key" in dct and dct["key"])
101+
19 19 |
102+
103+
RUF019.py:18:6: RUF019 [*] Unnecessary key check before dictionary access
104+
|
105+
16 | not ("key" in dct and dct["key"])
106+
17 |
107+
18 | bool("key" in dct and dct["key"])
108+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUF019
109+
19 |
110+
20 | # OK
111+
|
112+
= help: Replace with `dict.get`
113+
114+
Safe fix
115+
15 15 |
116+
16 16 | not ("key" in dct and dct["key"])
117+
17 17 |
118+
18 |-bool("key" in dct and dct["key"])
119+
18 |+bool(dct.get("key"))
120+
19 19 |
121+
20 20 | # OK
122+
21 21 | v = "k" in d and d["k"]

0 commit comments

Comments
 (0)