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
|
from dataclasses import dataclass
from mypy.nodes import CallExpr, MemberExpr, NameExpr
from refurb.checks.pathlib.util import is_pathlike
from refurb.error import Error
@dataclass
class ErrorInfo(Error):
"""
When removing a file, use the more modern `Path.unlink()` method instead of
`os.remove()` or `os.unlink()`: The `pathlib` module allows for more
flexibility when it comes to traversing folders, building file paths, and
accessing/modifying files.
Bad:
```
import os
os.remove("filename")
```
Good:
```
from pathlib import Path
Path("filename").unlink()
```
"""
name = "use-pathlib-unlink"
code = 144
categories = ("pathlib",)
def check(node: CallExpr, errors: list[Error]) -> None:
match node:
case CallExpr(
callee=(MemberExpr() | NameExpr()) as expr,
args=[arg],
) if expr.fullname in {"os.remove", "os.unlink"}:
replace = "x.unlink()" if is_pathlike(arg) else "Path(x).unlink()"
errors.append(
ErrorInfo.from_node(node, f"Replace `os.{expr.name}(x)` with `{replace}`")
)
|