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
|
from dataclasses import dataclass
from mypy.nodes import CallExpr, RefExpr
from refurb.checks.common import normalize_os_path
from refurb.checks.pathlib.util import is_pathlike
from refurb.error import Error
@dataclass
class ErrorInfo(Error):
"""
When checking whether a file exists or not, try and use the more modern
`pathlib` module instead of `os.path`.
Bad:
```
import os
if os.path.exists("filename"):
pass
```
Good:
```
from pathlib import Path
if Path("filename").exists():
pass
```
"""
name = "use-pathlib-exists"
code = 141
categories = ("pathlib",)
def check(node: CallExpr, errors: list[Error]) -> None:
match node:
case CallExpr(
callee=RefExpr() as expr,
args=[arg],
) if normalize_os_path(expr.fullname or "") == "os.path.exists":
replace = "x.exists()" if is_pathlike(arg) else "Path(x).exists()"
errors.append(
ErrorInfo.from_node(node, f"Replace `os.path.exists(x)` with `{replace}`")
)
|