File: use_constants.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 (51 lines) | stat: -rw-r--r-- 929 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
from dataclasses import dataclass

from mypy.nodes import FloatExpr

from refurb.error import Error


@dataclass
class ErrorInfo(Error):
    """
    Don't hardcode math constants like pi, tau, or e, use the `math.pi`,
    `math.tau`, or `math.e` constants respectively.

    Bad:

    ```
    def area(r: float) -> float:
        return 3.1415 * r * r
    ```

    Good:

    ```
    import math

    def area(r: float) -> float:
        return math.pi * r * r
    ```
    """

    name = "use-math-constant"
    code = 152
    categories = ("math", "readability")


CONSTANTS = {
    "pi": "3.14",
    "e": "2.71",
    "tau": "6.28",
}


def check(node: FloatExpr, errors: list[Error]) -> None:
    num = str(node.value)

    if len(num) <= 3:
        return

    for name, value in CONSTANTS.items():
        if num.startswith(value):
            errors.append(ErrorInfo.from_node(node, f"Replace `{num}` with `math.{name}`"))