1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
from dataclasses import dataclass
from mypy.nodes import NameExpr
from mypy.patterns import AsPattern, ClassPattern
from refurb.error import Error
@dataclass
class ErrorInfo(Error):
"""
When pattern matching builtin classes such as `int()` and `str()`, don't
use an `as` pattern to bind to the value, since the most common builtin
classes can use positional patterns instead.
Bad:
```
match x:
case str() as name:
print(f"Hello {name}")
```
Good:
```
match x:
case str(name):
print(f"Hello {name}")
```
"""
name = "simplify-as-pattern-with-builtin"
code = 158
categories = ("pattern-matching", "readability")
BUILTIN_PATTERN_CLASSES = (
"builtins.bool",
"builtins.bytearray",
"builtins.bytes",
"builtins.dict",
"builtins.float",
"builtins.frozenset",
"builtins.int",
"builtins.list",
"builtins.set",
"builtins.str",
"builtins.tuple",
)
def check(node: AsPattern, errors: list[Error]) -> None:
match node:
case AsPattern(
pattern=ClassPattern(
class_ref=NameExpr(name=name, fullname=fullname),
positionals=[],
keyword_keys=[],
keyword_values=[],
)
) if fullname in BUILTIN_PATTERN_CLASSES:
errors.append(ErrorInfo.from_node(node, f"Replace `{name}() as x` with `{name}(x)`"))
|