Skip to content

Commit

Permalink
ENH: Add dict.get(key, None)dict.get(key) as SIM910 (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyoto7250 authored Mar 30, 2023
1 parent d3cb955 commit 21375ea
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ Current experimental rules:
* [`SIM907`](https://github.com/MartinThoma/flake8-simplify/issues/64): Use Optional[Type] instead of Union[Type, None] ([example](#SIM907))
* [`SIM908`](https://github.com/MartinThoma/flake8-simplify/issues/50): Use dict.get(key) ([example](#SIM908))
* [`SIM909`](https://github.com/MartinThoma/flake8-simplify/issues/114): Avoid reflexive assignments ([example](#SIM909))
* [`SIM910`](https://github.com/MartinThoma/flake8-simplify/issues/171): Avoid to use `dict.get(key, None)` ([example](#SIM910))

## Disabling Rules

Expand Down Expand Up @@ -614,3 +615,13 @@ foo = foo = 42
# Good
foo = 42
```

### SIM910

```python
# Bad
dict.get(key, None)

# Good
dict.get(key)
```
2 changes: 2 additions & 0 deletions flake8_simplify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
get_sim901,
get_sim905,
get_sim906,
get_sim910,
)
from flake8_simplify.rules.ast_classdef import get_sim120
from flake8_simplify.rules.ast_compare import get_sim118, get_sim300
Expand Down Expand Up @@ -74,6 +75,7 @@ def visit_Call(self, node: ast.Call) -> Any:
self.errors += get_sim901(node)
self.errors += get_sim905(node)
self.errors += get_sim906(node)
self.errors += get_sim910(Call(node))
self.generic_visit(node)

def visit_With(self, node: ast.With) -> Any:
Expand Down
53 changes: 53 additions & 0 deletions flake8_simplify/rules/ast_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import List, Tuple

# First party
from flake8_simplify.constants import BOOL_CONST_TYPES
from flake8_simplify.utils import Call, to_source

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -180,3 +181,55 @@ def get_os_path_join_args(node: ast.Call) -> List[str]:
)
)
return errors


def get_sim910(node: Call) -> List[Tuple[int, int, str]]:
"""
Get a list of all usages of "dict.get(key, None)"
Example AST
-----------
Expr(
value=Call(
func=Attribute(
value=Name(id='a_dict', ctx=Load()),
attr='get',
ctx=Load()
),
args=[
Name(id='key', ctx=Load()),
Constant(value=None)
],
keywords=[]
),
),
"""
RULE = "SIM910 Use '{expected}' instead of '{actual}'"
errors: List[Tuple[int, int, str]] = []
if not (
isinstance(node.func, ast.Attribute)
and node.func.attr == "get"
and isinstance(node.func.ctx, ast.Load)
):
return errors

# check the argument value
if not (
len(node.args) == 2
and isinstance(node.args[1], BOOL_CONST_TYPES)
and node.args[1].value is None
):
return errors

actual = to_source(node)
func = to_source(node.func)
key = to_source(node.args[0])
expected = f"{func}({key})"
errors.append(
(
node.lineno,
node.col_offset,
RULE.format(actual=actual, expected=expected),
)
)
return errors
23 changes: 23 additions & 0 deletions tests/test_900_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,26 @@ def test_sim909_false_positives(s):
results = _results(s)
for result in results:
assert "SIM909" not in result


@pytest.mark.parametrize(
("s", "msg"),
(
(
"d.get(key, None)",
"1:0 SIM910 Use 'd.get(key)' instead of 'd.get(key, None)'",
),
(
"d.get('key', None)",
"1:0 SIM910 Use 'd.get(\"key\")' instead of 'd.get('key', None)'",
),
(
"d.get(key)",
None,
),
),
)
def test_sim910(s, msg):
expected = {msg} if msg is not None else set()
results = _results(s)
assert results == expected

0 comments on commit 21375ea

Please sign in to comment.