Skip to content

Commit a818e28

Browse files
committed
Use python-typing-update on pylint/checkers directory
1 parent 05e50e2 commit a818e28

27 files changed

+259
-255
lines changed

pylint/checkers/__init__.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,9 @@
4141
4242
"""
4343

44+
from __future__ import annotations
45+
4446
import sys
45-
from typing import List, Optional, Tuple, Union
4647

4748
from pylint.checkers.base_checker import BaseChecker, BaseTokenChecker
4849
from pylint.checkers.deprecated import DeprecatedMixin
@@ -57,25 +58,25 @@
5758

5859
def table_lines_from_stats(
5960
stats: LinterStats,
60-
old_stats: Optional[LinterStats],
61+
old_stats: LinterStats | None,
6162
stat_type: Literal["duplicated_lines", "message_types"],
62-
) -> List[str]:
63+
) -> list[str]:
6364
"""Get values listed in <columns> from <stats> and <old_stats>,
6465
and return a formatted list of values.
6566
6667
The return value is designed to be given to a ureport.Table object
6768
"""
68-
lines: List[str] = []
69+
lines: list[str] = []
6970
if stat_type == "duplicated_lines":
70-
new: List[Tuple[str, Union[int, float]]] = [
71+
new: list[tuple[str, int | float]] = [
7172
("nb_duplicated_lines", stats.duplicated_lines["nb_duplicated_lines"]),
7273
(
7374
"percent_duplicated_lines",
7475
stats.duplicated_lines["percent_duplicated_lines"],
7576
),
7677
]
7778
if old_stats:
78-
old: List[Tuple[str, Union[str, int, float]]] = [
79+
old: list[tuple[str, str | int | float]] = [
7980
(
8081
"nb_duplicated_lines",
8182
old_stats.duplicated_lines["nb_duplicated_lines"],

pylint/checkers/async.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
"""Checker for anything related to the async protocol (PEP 492)."""
66

7+
from __future__ import annotations
8+
79
import sys
810
from typing import TYPE_CHECKING
911

@@ -91,5 +93,5 @@ def visit_asyncwith(self, node: nodes.AsyncWith) -> None:
9193
)
9294

9395

94-
def register(linter: "PyLinter") -> None:
96+
def register(linter: PyLinter) -> None:
9597
linter.register_checker(AsyncChecker(linter))

pylint/checkers/base_checker.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
33
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
44

5+
from __future__ import annotations
6+
57
import functools
68
import warnings
79
from inspect import cleandoc
8-
from typing import TYPE_CHECKING, Any, Optional
10+
from typing import TYPE_CHECKING, Any
911

1012
from astroid import nodes
1113

@@ -37,7 +39,7 @@ class BaseChecker(_ArgumentsProvider):
3739
# mark this checker as enabled or not.
3840
enabled: bool = True
3941

40-
def __init__(self, linter: "PyLinter") -> None:
42+
def __init__(self, linter: PyLinter) -> None:
4143
"""Checker instances should have the linter as argument."""
4244
if self.name is not None:
4345
self.name = self.name.lower()
@@ -114,13 +116,13 @@ def get_full_documentation(self, msgs, options, reports, doc=None, module=None):
114116
def add_message(
115117
self,
116118
msgid: str,
117-
line: Optional[int] = None,
118-
node: Optional[nodes.NodeNG] = None,
119+
line: int | None = None,
120+
node: nodes.NodeNG | None = None,
119121
args: Any = None,
120-
confidence: Optional[Confidence] = None,
121-
col_offset: Optional[int] = None,
122-
end_lineno: Optional[int] = None,
123-
end_col_offset: Optional[int] = None,
122+
confidence: Confidence | None = None,
123+
col_offset: int | None = None,
124+
end_lineno: int | None = None,
125+
end_col_offset: int | None = None,
124126
) -> None:
125127
self.linter.add_message(
126128
msgid, line, node, args, confidence, col_offset, end_lineno, end_col_offset

pylint/checkers/deprecated.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@
33
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
44

55
"""Checker mixin for deprecated functionality."""
6+
7+
from __future__ import annotations
8+
69
from itertools import chain
7-
from typing import Any, Container, Iterable, Tuple, Union
10+
from typing import Any, Container, Iterable
811

912
import astroid
1013
from astroid import nodes
@@ -124,9 +127,7 @@ def deprecated_methods(self) -> Container[str]:
124127
# pylint: disable=no-self-use
125128
return ()
126129

127-
def deprecated_arguments(
128-
self, method: str
129-
) -> Iterable[Tuple[Union[int, None], str]]:
130+
def deprecated_arguments(self, method: str) -> Iterable[tuple[int | None, str]]:
130131
"""Callback returning the deprecated arguments of method/function.
131132
132133
Args:

pylint/checkers/design_analysis.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
"""Check for signs of poor design."""
66

7+
from __future__ import annotations
8+
79
import re
810
import sys
911
from collections import defaultdict
10-
from typing import TYPE_CHECKING, FrozenSet, Iterator, List, Set, cast
12+
from typing import TYPE_CHECKING, Iterator, List, cast
1113

1214
import astroid
1315
from astroid import nodes
@@ -229,7 +231,7 @@ def _count_methods_in_class(node):
229231

230232

231233
def _get_parents_iter(
232-
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
234+
node: nodes.ClassDef, ignored_parents: frozenset[str]
233235
) -> Iterator[nodes.ClassDef]:
234236
r"""Get parents of ``node``, excluding ancestors of ``ignored_parents``.
235237
@@ -246,7 +248,7 @@ def _get_parents_iter(
246248
And ``ignored_parents`` is ``{"E"}``, then this function will return
247249
``{A, B, C, D}`` -- both ``E`` and its ancestors are excluded.
248250
"""
249-
parents: Set[nodes.ClassDef] = set()
251+
parents: set[nodes.ClassDef] = set()
250252
to_explore = cast(List[nodes.ClassDef], list(node.ancestors(recurs=False)))
251253
while to_explore:
252254
parent = to_explore.pop()
@@ -265,8 +267,8 @@ def _get_parents_iter(
265267

266268

267269
def _get_parents(
268-
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
269-
) -> Set[nodes.ClassDef]:
270+
node: nodes.ClassDef, ignored_parents: frozenset[str]
271+
) -> set[nodes.ClassDef]:
270272
return set(_get_parents_iter(node, ignored_parents))
271273

272274

@@ -649,5 +651,5 @@ def _inc_branch(self, node, branchesnum=1):
649651
self._branches[node.scope()] += branchesnum
650652

651653

652-
def register(linter: "PyLinter") -> None:
654+
def register(linter: PyLinter) -> None:
653655
linter.register_checker(MisdesignChecker(linter))

pylint/checkers/dunder_methods.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
33
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
44

5+
from __future__ import annotations
6+
57
from typing import TYPE_CHECKING
68

79
from astroid import nodes
@@ -155,5 +157,5 @@ def visit_call(self, node: nodes.Call) -> None:
155157
)
156158

157159

158-
def register(linter: "PyLinter") -> None:
160+
def register(linter: PyLinter) -> None:
159161
linter.register_checker(DunderCallChecker(linter))

pylint/checkers/ellipsis_checker.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
44

55
"""Ellipsis checker for Python code."""
6+
7+
from __future__ import annotations
8+
69
from typing import TYPE_CHECKING
710

811
from astroid import nodes
@@ -53,5 +56,5 @@ def visit_const(self, node: nodes.Const) -> None:
5356
self.add_message("unnecessary-ellipsis", node=node)
5457

5558

56-
def register(linter: "PyLinter") -> None:
59+
def register(linter: PyLinter) -> None:
5760
linter.register_checker(EllipsisChecker(linter))

pylint/checkers/exceptions.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
44

55
"""Checks for various exception related errors."""
6+
7+
from __future__ import annotations
8+
69
import builtins
710
import inspect
8-
from typing import TYPE_CHECKING, Any, List, Optional
11+
from typing import TYPE_CHECKING, Any
912

1013
import astroid
1114
from astroid import nodes, objects
@@ -44,7 +47,7 @@ def _annotated_unpack_infer(stmt, context=None):
4447
yield stmt, inferred
4548

4649

47-
def _is_raising(body: List) -> bool:
50+
def _is_raising(body: list) -> bool:
4851
"""Return whether the given statement node raises an exception."""
4952
return any(isinstance(node, nodes.Raise) for node in body)
5053

@@ -394,8 +397,8 @@ def _check_catching_non_exception(self, handler, exc, part):
394397
def _check_try_except_raise(self, node):
395398
def gather_exceptions_from_handler(
396399
handler,
397-
) -> Optional[List[nodes.NodeNG]]:
398-
exceptions: List[nodes.NodeNG] = []
400+
) -> list[nodes.NodeNG] | None:
401+
exceptions: list[nodes.NodeNG] = []
399402
if handler.type:
400403
exceptions_in_handler = utils.safe_infer(handler.type)
401404
if isinstance(exceptions_in_handler, nodes.Tuple):
@@ -474,7 +477,7 @@ def visit_compare(self, node: nodes.Compare) -> None:
474477
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
475478
"""Check for empty except."""
476479
self._check_try_except_raise(node)
477-
exceptions_classes: List[Any] = []
480+
exceptions_classes: list[Any] = []
478481
nb_handlers = len(node.handlers)
479482
for index, handler in enumerate(node.handlers):
480483
if handler.type is None:
@@ -539,5 +542,5 @@ def visit_tryexcept(self, node: nodes.TryExcept) -> None:
539542
exceptions_classes += [exc for _, exc in exceptions]
540543

541544

542-
def register(linter: "PyLinter") -> None:
545+
def register(linter: PyLinter) -> None:
543546
linter.register_checker(ExceptionsChecker(linter))

pylint/checkers/format.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111
Some parts of the process_token method is based from The Tab Nanny std module.
1212
"""
1313

14+
from __future__ import annotations
15+
1416
import tokenize
1517
from functools import reduce
16-
from typing import TYPE_CHECKING, List
18+
from typing import TYPE_CHECKING
1719

1820
from astroid import nodes
1921

@@ -322,7 +324,7 @@ def process_module(self, _node: nodes.Module) -> None:
322324

323325
# pylint: disable-next=too-many-return-statements
324326
def _check_keyword_parentheses(
325-
self, tokens: List[tokenize.TokenInfo], start: int
327+
self, tokens: list[tokenize.TokenInfo], start: int
326328
) -> None:
327329
"""Check that there are not unnecessary parentheses after a keyword.
328330
@@ -670,7 +672,7 @@ def is_line_length_check_activated(pylint_pattern_match_object) -> bool:
670672
return True
671673

672674
@staticmethod
673-
def specific_splitlines(lines: str) -> List[str]:
675+
def specific_splitlines(lines: str) -> list[str]:
674676
"""Split lines according to universal newlines except those in a specific sets."""
675677
unsplit_ends = {
676678
"\x0b", # synonym of \v
@@ -768,5 +770,5 @@ def check_indent_level(self, string, expected, line_num):
768770
)
769771

770772

771-
def register(linter: "PyLinter") -> None:
773+
def register(linter: PyLinter) -> None:
772774
linter.register_checker(FormatChecker(linter))

pylint/checkers/imports.py

+15-15
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
"""Imports checkers for Python code."""
66

7+
from __future__ import annotations
8+
79
import collections
810
import copy
911
import os
10-
from typing import TYPE_CHECKING, Any, Dict, List, Set, Tuple, Union
12+
from typing import TYPE_CHECKING, Any
1113

1214
import astroid
1315
from astroid import nodes
@@ -127,7 +129,7 @@ def _repr_tree_defs(data, indent_str=None):
127129
return "\n".join(lines)
128130

129131

130-
def _dependencies_graph(filename: str, dep_info: Dict[str, Set[str]]) -> str:
132+
def _dependencies_graph(filename: str, dep_info: dict[str, set[str]]) -> str:
131133
"""Write dependencies as a dot (graphviz) file."""
132134
done = {}
133135
printer = DotBackend(os.path.splitext(os.path.basename(filename))[0], rankdir="LR")
@@ -147,7 +149,7 @@ def _dependencies_graph(filename: str, dep_info: Dict[str, Set[str]]) -> str:
147149

148150

149151
def _make_graph(
150-
filename: str, dep_info: Dict[str, Set[str]], sect: Section, gtype: str
152+
filename: str, dep_info: dict[str, set[str]], sect: Section, gtype: str
151153
):
152154
"""Generate a dependencies graph and add some information about it in the
153155
report's section
@@ -370,15 +372,15 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
370372
),
371373
)
372374

373-
def __init__(self, linter: "PyLinter") -> None:
375+
def __init__(self, linter: PyLinter) -> None:
374376
BaseChecker.__init__(self, linter)
375377
self.import_graph: collections.defaultdict = collections.defaultdict(set)
376-
self._imports_stack: List[Tuple[Any, Any]] = []
378+
self._imports_stack: list[tuple[Any, Any]] = []
377379
self._first_non_import_node = None
378-
self._module_pkg: Dict[
380+
self._module_pkg: dict[
379381
Any, Any
380382
] = {} # mapping of modules to the pkg they belong in
381-
self._allow_any_import_level: Set[Any] = set()
383+
self._allow_any_import_level: set[Any] = set()
382384
self.reports = (
383385
("RP0401", "External dependencies", self._report_external_dependencies),
384386
("RP0402", "Modules dependencies graph", self._report_dependencies_graph),
@@ -478,8 +480,8 @@ def leave_module(self, node: nodes.Module) -> None:
478480
std_imports, ext_imports, loc_imports = self._check_imports_order(node)
479481

480482
# Check that imports are grouped by package within a given category
481-
met_import: Set[str] = set() # set for 'import x' style
482-
met_from: Set[str] = set() # set for 'from x import y' style
483+
met_import: set[str] = set() # set for 'import x' style
484+
met_from: set[str] = set() # set for 'from x import y' style
483485
current_package = None
484486
for import_node, import_name in std_imports + ext_imports + loc_imports:
485487
met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import
@@ -746,7 +748,7 @@ def _get_imported_module(self, importnode, modname):
746748
return None
747749

748750
def _add_imported_module(
749-
self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str
751+
self, node: nodes.Import | nodes.ImportFrom, importedmodname: str
750752
) -> None:
751753
"""Notify an imported module, used to analyze dependencies."""
752754
module_file = node.root().file
@@ -775,7 +777,7 @@ def _add_imported_module(
775777
self._module_pkg[context_name] = context_name.rsplit(".", 1)[0]
776778

777779
# handle dependencies
778-
dependencies_stat: Dict[str, Set[str]] = self.linter.stats.dependencies
780+
dependencies_stat: dict[str, set[str]] = self.linter.stats.dependencies
779781
importedmodnames = dependencies_stat.setdefault(importedmodname, set())
780782
if context_name not in importedmodnames:
781783
importedmodnames.add(context_name)
@@ -797,9 +799,7 @@ def _check_preferred_module(self, node, mod_path):
797799
args=(self.preferred_modules[mod_path], mod_path),
798800
)
799801

800-
def _check_import_as_rename(
801-
self, node: Union[nodes.Import, nodes.ImportFrom]
802-
) -> None:
802+
def _check_import_as_rename(self, node: nodes.Import | nodes.ImportFrom) -> None:
803803
names = node.names
804804
for name in names:
805805
if not all(name):
@@ -935,5 +935,5 @@ def _check_toplevel(self, node):
935935
)
936936

937937

938-
def register(linter: "PyLinter") -> None:
938+
def register(linter: PyLinter) -> None:
939939
linter.register_checker(ImportsChecker(linter))

0 commit comments

Comments
 (0)