Skip to content

Commit

Permalink
Avoid key-in-dict violations for self accesses (#6165)
Browse files Browse the repository at this point in the history
Closes #6163.
  • Loading branch information
charliermarsh committed Jul 29, 2023
1 parent 646ff64 commit 4802c7c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
10 changes: 10 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_simplify/SIM118.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,13 @@
(k for k in obj.keys()) # SIM118

key in (obj or {}).keys() # SIM118

from typing import KeysView


class Foo:
def keys(self) -> KeysView[object]:
...

def __contains__(self, key: object) -> bool:
return key in self.keys() # OK
14 changes: 13 additions & 1 deletion crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,25 @@ fn key_in_dict(
return;
}

let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() else {
let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func.as_ref() else {
return;
};
if attr != "keys" {
return;
}

// Ignore `self.keys()`, which will almost certainly be intentional, as in:
// ```python
// def __contains__(self, key: object) -> bool:
// return key in self.keys()
// ```
if value
.as_name_expr()
.map_or(false, |name| matches!(name.id.as_str(), "self"))
{
return;
}

// Slice exact content to preserve formatting.
let left_content = checker.locator().slice(left.range());
let Ok(value_content) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,13 +265,16 @@ SIM118.py:30:8: SIM118 [*] Use `k in obj` instead of `k in obj.keys()`
30 |+(k for k in obj) # SIM118
31 31 |
32 32 | key in (obj or {}).keys() # SIM118
33 33 |

SIM118.py:32:1: SIM118 [*] Use `key in (obj or {})` instead of `key in (obj or {}).keys()`
|
30 | (k for k in obj.keys()) # SIM118
31 |
32 | key in (obj or {}).keys() # SIM118
| ^^^^^^^^^^^^^^^^^^^^^^^^^ SIM118
33 |
34 | from typing import KeysView
|
= help: Convert to `key in (obj or {})`

Expand All @@ -281,5 +284,8 @@ SIM118.py:32:1: SIM118 [*] Use `key in (obj or {})` instead of `key in (obj or {
31 31 |
32 |-key in (obj or {}).keys() # SIM118
32 |+key in (obj or {}) # SIM118
33 33 |
34 34 | from typing import KeysView
35 35 |


0 comments on commit 4802c7c

Please sign in to comment.