File: use_operators.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 (154 lines) | stat: -rw-r--r-- 3,567 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
from dataclasses import dataclass

from mypy.nodes import (
    ArgKind,
    Block,
    ComparisonExpr,
    FuncItem,
    LambdaExpr,
    NameExpr,
    OpExpr,
    ReturnStmt,
    UnaryExpr,
)

from refurb.checks.common import _stringify
from refurb.error import Error


@dataclass
class ErrorInfo(Error):
    """
    Don't write lambdas/functions to wrap builtin operators, use the `operator`
    module instead:

    Bad:

    ```
    from functools import reduce

    nums = [1, 2, 3]

    print(reduce(lambda x, y: x + y, nums))  # 6
    ```

    Good:

    ```
    from functools import reduce
    from operator import add

    nums = [1, 2, 3]

    print(reduce(add, nums))  # 6
    ```
    """

    name = "use-operator"
    code = 118
    categories = ("operator",)


BINARY_OPERATORS = {
    "+": "add",
    "in": "contains",
    "/": "truediv",
    "//": "floordiv",
    "&": "and_",
    "^": "xor",
    "|": "or_",
    "**": "pow",
    "is": "is_",
    "is not": "is_not",
    "<<": "lshift",
    "%": "mod",
    "*": "mul",
    "@": "matmul",
    ">>": "rshift",
    "-": "sub",
    "<": "lt",
    "<=": "le",
    "==": "eq",
    "!=": "ne",
    ">=": "ge",
    ">": "gt",
}

UNARY_OPERATORS = {
    "~": "invert",
    "-": "neg",
    "not": "not_",
    "+": "pos",
}


def check(node: FuncItem, errors: list[Error]) -> None:
    func_type = get_function_type(node)

    match node:
        case FuncItem(
            arg_names=[lhs_name, rhs_name],
            arg_kinds=[ArgKind.ARG_POS, ArgKind.ARG_POS],
            body=Block(
                body=[
                    ReturnStmt(
                        expr=OpExpr(
                            op=op,
                            left=NameExpr(name=expr_lhs),
                            right=NameExpr(name=expr_rhs),
                        )
                        | ComparisonExpr(
                            operators=[op],
                            operands=[
                                NameExpr(name=expr_lhs),
                                NameExpr(name=expr_rhs),
                            ],
                        ),
                    )
                ]
            ),
        ) if func_name := BINARY_OPERATORS.get(op):
            if func_name == "contains":
                # operator.contains has reversed parameters
                expr_lhs, expr_rhs = expr_rhs, expr_lhs

            if lhs_name == expr_lhs and rhs_name == expr_rhs:
                errors.append(
                    ErrorInfo.from_node(
                        node,
                        f"Replace {func_type} with `operator.{func_name}`",
                    )
                )

        case FuncItem(
            arg_names=[name],
            arg_kinds=[ArgKind.ARG_POS],
            body=Block(
                body=[
                    ReturnStmt(
                        expr=UnaryExpr(
                            op=op,
                            expr=NameExpr(name=expr_name),
                        )
                    )
                ]
            ),
        ) if name == expr_name:
            if func_name := UNARY_OPERATORS.get(op):
                errors.append(
                    ErrorInfo.from_node(
                        node,
                        f"Replace {func_type} with `operator.{func_name}`",
                    )
                )


def get_function_type(node: FuncItem) -> str:
    if isinstance(node, LambdaExpr):
        try:
            return f"`{_stringify(node)}`"

        except ValueError:
            return "lambda"

    return "function"