Treat not operations as boolean tests (#12301)

## Summary

Closes https://github.com/astral-sh/ruff/issues/12285.
This commit is contained in:
Charlie Marsh 2024-07-12 05:53:37 -07:00 committed by GitHub
parent 6febd96dfe
commit 4e6ecb2348
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 52 additions and 1 deletions

View file

@ -13,6 +13,10 @@ if (k) in d and d[k]:
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"]

View file

@ -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,

View file

@ -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"]