check_builtin_literals.py 2.9 KB
Newer Older
1
2
import argparse
import ast
3
from typing import List
4
from typing import NamedTuple
5
6
7
from typing import Optional
from typing import Sequence
from typing import Set
8
9
10
11
12
13
14
15
16
17
18
19
20


BUILTIN_TYPES = {
    'complex': '0j',
    'dict': '{}',
    'float': '0.0',
    'int': '0',
    'list': '[]',
    'str': "''",
    'tuple': '()',
}


21
22
23
24
class Call(NamedTuple):
    name: str
    line: int
    column: int
25
26


27
class Visitor(ast.NodeVisitor):
28
29
30
31
32
33
    def __init__(
            self,
            ignore: Optional[Sequence[str]] = None,
            allow_dict_kwargs: bool = True,
    ) -> None:
        self.builtin_type_calls: List[Call] = []
34
35
36
        self.ignore = set(ignore) if ignore else set()
        self.allow_dict_kwargs = allow_dict_kwargs

37
38
    def _check_dict_call(self, node: ast.Call) -> bool:
        return self.allow_dict_kwargs and bool(node.keywords)
39

40
    def visit_Call(self, node: ast.Call) -> None:
41
        if not isinstance(node.func, ast.Name):
42
43
44
45
            # Ignore functions that are object attributes (`foo.bar()`).
            # Assume that if the user calls `builtins.list()`, they know what
            # they're doing.
            return
46
47
48
49
50
51
52
        if node.func.id not in set(BUILTIN_TYPES).difference(self.ignore):
            return
        if node.func.id == 'dict' and self._check_dict_call(node):
            return
        elif node.args:
            return
        self.builtin_type_calls.append(
53
            Call(node.func.id, node.lineno, node.col_offset),
54
55
56
        )


57
58
59
60
61
def check_file(
        filename: str,
        ignore: Optional[Sequence[str]] = None,
        allow_dict_kwargs: bool = True,
) -> List[Call]:
62
63
    with open(filename, 'rb') as f:
        tree = ast.parse(f.read(), filename=filename)
64
    visitor = Visitor(ignore=ignore, allow_dict_kwargs=allow_dict_kwargs)
65
66
67
68
    visitor.visit(tree)
    return visitor.builtin_type_calls


69
def parse_ignore(value: str) -> Set[str]:
70
    return set(value.split(','))
71

72

73
def main(argv: Optional[Sequence[str]] = None) -> int:
74
75
76
77
    parser = argparse.ArgumentParser()
    parser.add_argument('filenames', nargs='*')
    parser.add_argument('--ignore', type=parse_ignore, default=set())

78
79
    mutex = parser.add_mutually_exclusive_group(required=False)
    mutex.add_argument('--allow-dict-kwargs', action='store_true')
80
81
82
83
    mutex.add_argument(
        '--no-allow-dict-kwargs',
        dest='allow_dict_kwargs', action='store_false',
    )
84
    mutex.set_defaults(allow_dict_kwargs=True)
85

86
    args = parser.parse_args(argv)
87
88
89

    rc = 0
    for filename in args.filenames:
90
        calls = check_file(
91
92
93
94
95
96
97
98
            filename,
            ignore=args.ignore,
            allow_dict_kwargs=args.allow_dict_kwargs,
        )
        if calls:
            rc = rc or 1
        for call in calls:
            print(
99
100
                f'{filename}:{call.line}:{call.column}: '
                f'replace {call.name}() with {BUILTIN_TYPES[call.name]}',
101
102
103
104
105
            )
    return rc


if __name__ == '__main__':
106
    exit(main())