File: write_text.py

package info (click to toggle)
python-refurb 1.27.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,700 kB
  • sloc: python: 9,468; makefile: 40; sh: 6
file content (55 lines) | stat: -rw-r--r-- 1,511 bytes parent folder | download
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
from dataclasses import dataclass

from mypy.nodes import Block, CallExpr, ExpressionStmt, MemberExpr, NameExpr, StrExpr, WithStmt

from refurb.error import Error


@dataclass
class ErrorInfo(Error):
    """
    When you just want to save some contents to a file, using a `with` block is
    a bit overkill. Instead you can use pathlib's `write_text()` method:

    Bad:

    ```
    with open(filename, "w") as f:
        f.write("hello world")
    ```

    Good:

    ```
    Path(filename).write_text("hello world")
    ```
    """

    name = "use-pathlib-write-text-write-bytes"
    code = 103
    categories = ("pathlib",)


def check(node: WithStmt, errors: list[Error]) -> None:
    match node:
        case WithStmt(
            expr=[CallExpr(callee=NameExpr(name="open"), args=[_, StrExpr(value=mode)])],
            target=[NameExpr(name=with_name)],
            body=Block(
                body=[
                    ExpressionStmt(
                        expr=CallExpr(
                            callee=MemberExpr(expr=NameExpr(name=write_name), name="write")
                        )
                    )
                ]
            ),
        ) if with_name == write_name and "w" in mode:
            func = "write_bytes" if ("b" in mode) else "write_text"

            errors.append(
                ErrorInfo.from_node(
                    node,
                    f"Replace `with open(x, ...) as f: f.write(y)` with `Path(x).{func}(y)`",  # noqa: E501
                )
            )