Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use python-typing-update on pylint/checkers directory #6312

Merged
merged 1 commit into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions pylint/checkers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@

"""

from __future__ import annotations

import sys
from typing import List, Optional, Tuple, Union

from pylint.checkers.base_checker import BaseChecker, BaseTokenChecker
from pylint.checkers.deprecated import DeprecatedMixin
Expand All @@ -57,25 +58,25 @@

def table_lines_from_stats(
stats: LinterStats,
old_stats: Optional[LinterStats],
old_stats: LinterStats | None,
stat_type: Literal["duplicated_lines", "message_types"],
) -> List[str]:
) -> list[str]:
"""Get values listed in <columns> from <stats> and <old_stats>,
and return a formatted list of values.

The return value is designed to be given to a ureport.Table object
"""
lines: List[str] = []
lines: list[str] = []
if stat_type == "duplicated_lines":
new: List[Tuple[str, Union[int, float]]] = [
new: list[tuple[str, int | float]] = [
("nb_duplicated_lines", stats.duplicated_lines["nb_duplicated_lines"]),
(
"percent_duplicated_lines",
stats.duplicated_lines["percent_duplicated_lines"],
),
]
if old_stats:
old: List[Tuple[str, Union[str, int, float]]] = [
old: list[tuple[str, str | int | float]] = [
(
"nb_duplicated_lines",
old_stats.duplicated_lines["nb_duplicated_lines"],
Expand Down
4 changes: 3 additions & 1 deletion pylint/checkers/async.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

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

from __future__ import annotations

import sys
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -91,5 +93,5 @@ def visit_asyncwith(self, node: nodes.AsyncWith) -> None:
)


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(AsyncChecker(linter))
18 changes: 10 additions & 8 deletions pylint/checkers/base_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

from __future__ import annotations

import functools
import warnings
from inspect import cleandoc
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any

from astroid import nodes

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

def __init__(self, linter: "PyLinter") -> None:
def __init__(self, linter: PyLinter) -> None:
"""Checker instances should have the linter as argument."""
if self.name is not None:
self.name = self.name.lower()
Expand Down Expand Up @@ -114,13 +116,13 @@ def get_full_documentation(self, msgs, options, reports, doc=None, module=None):
def add_message(
self,
msgid: str,
line: Optional[int] = None,
node: Optional[nodes.NodeNG] = None,
line: int | None = None,
node: nodes.NodeNG | None = None,
args: Any = None,
confidence: Optional[Confidence] = None,
col_offset: Optional[int] = None,
end_lineno: Optional[int] = None,
end_col_offset: Optional[int] = None,
confidence: Confidence | None = None,
col_offset: int | None = None,
end_lineno: int | None = None,
end_col_offset: int | None = None,
) -> None:
self.linter.add_message(
msgid, line, node, args, confidence, col_offset, end_lineno, end_col_offset
Expand Down
9 changes: 5 additions & 4 deletions pylint/checkers/deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Checker mixin for deprecated functionality."""

from __future__ import annotations

from itertools import chain
from typing import Any, Container, Iterable, Tuple, Union
from typing import Any, Container, Iterable

import astroid
from astroid import nodes
Expand Down Expand Up @@ -124,9 +127,7 @@ def deprecated_methods(self) -> Container[str]:
# pylint: disable=no-self-use
return ()

def deprecated_arguments(
self, method: str
) -> Iterable[Tuple[Union[int, None], str]]:
def deprecated_arguments(self, method: str) -> Iterable[tuple[int | None, str]]:
"""Callback returning the deprecated arguments of method/function.

Args:
Expand Down
14 changes: 8 additions & 6 deletions pylint/checkers/design_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

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

from __future__ import annotations

import re
import sys
from collections import defaultdict
from typing import TYPE_CHECKING, FrozenSet, Iterator, List, Set, cast
from typing import TYPE_CHECKING, Iterator, List, cast

import astroid
from astroid import nodes
Expand Down Expand Up @@ -229,7 +231,7 @@ def _count_methods_in_class(node):


def _get_parents_iter(
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
node: nodes.ClassDef, ignored_parents: frozenset[str]
) -> Iterator[nodes.ClassDef]:
r"""Get parents of ``node``, excluding ancestors of ``ignored_parents``.

Expand All @@ -246,7 +248,7 @@ def _get_parents_iter(
And ``ignored_parents`` is ``{"E"}``, then this function will return
``{A, B, C, D}`` -- both ``E`` and its ancestors are excluded.
"""
parents: Set[nodes.ClassDef] = set()
parents: set[nodes.ClassDef] = set()
to_explore = cast(List[nodes.ClassDef], list(node.ancestors(recurs=False)))
while to_explore:
parent = to_explore.pop()
Expand All @@ -265,8 +267,8 @@ def _get_parents_iter(


def _get_parents(
node: nodes.ClassDef, ignored_parents: FrozenSet[str]
) -> Set[nodes.ClassDef]:
node: nodes.ClassDef, ignored_parents: frozenset[str]
) -> set[nodes.ClassDef]:
return set(_get_parents_iter(node, ignored_parents))


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


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(MisdesignChecker(linter))
4 changes: 3 additions & 1 deletion pylint/checkers/dunder_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

from __future__ import annotations

from typing import TYPE_CHECKING

from astroid import nodes
Expand Down Expand Up @@ -155,5 +157,5 @@ def visit_call(self, node: nodes.Call) -> None:
)


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(DunderCallChecker(linter))
5 changes: 4 additions & 1 deletion pylint/checkers/ellipsis_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Ellipsis checker for Python code."""

from __future__ import annotations

from typing import TYPE_CHECKING

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


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(EllipsisChecker(linter))
15 changes: 9 additions & 6 deletions pylint/checkers/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Checks for various exception related errors."""

from __future__ import annotations

import builtins
import inspect
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, Any

import astroid
from astroid import nodes, objects
Expand Down Expand Up @@ -44,7 +47,7 @@ def _annotated_unpack_infer(stmt, context=None):
yield stmt, inferred


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

Expand Down Expand Up @@ -394,8 +397,8 @@ def _check_catching_non_exception(self, handler, exc, part):
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(
handler,
) -> Optional[List[nodes.NodeNG]]:
exceptions: List[nodes.NodeNG] = []
) -> list[nodes.NodeNG] | None:
exceptions: list[nodes.NodeNG] = []
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, nodes.Tuple):
Expand Down Expand Up @@ -474,7 +477,7 @@ def visit_compare(self, node: nodes.Compare) -> None:
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Check for empty except."""
self._check_try_except_raise(node)
exceptions_classes: List[Any] = []
exceptions_classes: list[Any] = []
nb_handlers = len(node.handlers)
for index, handler in enumerate(node.handlers):
if handler.type is None:
Expand Down Expand Up @@ -539,5 +542,5 @@ def visit_tryexcept(self, node: nodes.TryExcept) -> None:
exceptions_classes += [exc for _, exc in exceptions]


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(ExceptionsChecker(linter))
10 changes: 6 additions & 4 deletions pylint/checkers/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
Some parts of the process_token method is based from The Tab Nanny std module.
"""

from __future__ import annotations

import tokenize
from functools import reduce
from typing import TYPE_CHECKING, List
from typing import TYPE_CHECKING

from astroid import nodes

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

# pylint: disable-next=too-many-return-statements
def _check_keyword_parentheses(
self, tokens: List[tokenize.TokenInfo], start: int
self, tokens: list[tokenize.TokenInfo], start: int
) -> None:
"""Check that there are not unnecessary parentheses after a keyword.

Expand Down Expand Up @@ -670,7 +672,7 @@ def is_line_length_check_activated(pylint_pattern_match_object) -> bool:
return True

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


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(FormatChecker(linter))
30 changes: 15 additions & 15 deletions pylint/checkers/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

"""Imports checkers for Python code."""

from __future__ import annotations

import collections
import copy
import os
from typing import TYPE_CHECKING, Any, Dict, List, Set, Tuple, Union
from typing import TYPE_CHECKING, Any

import astroid
from astroid import nodes
Expand Down Expand Up @@ -127,7 +129,7 @@ def _repr_tree_defs(data, indent_str=None):
return "\n".join(lines)


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


def _make_graph(
filename: str, dep_info: Dict[str, Set[str]], sect: Section, gtype: str
filename: str, dep_info: dict[str, set[str]], sect: Section, gtype: str
):
"""Generate a dependencies graph and add some information about it in the
report's section
Expand Down Expand Up @@ -370,15 +372,15 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
),
)

def __init__(self, linter: "PyLinter") -> None:
def __init__(self, linter: PyLinter) -> None:
BaseChecker.__init__(self, linter)
self.import_graph: collections.defaultdict = collections.defaultdict(set)
self._imports_stack: List[Tuple[Any, Any]] = []
self._imports_stack: list[tuple[Any, Any]] = []
self._first_non_import_node = None
self._module_pkg: Dict[
self._module_pkg: dict[
Any, Any
] = {} # mapping of modules to the pkg they belong in
self._allow_any_import_level: Set[Any] = set()
self._allow_any_import_level: set[Any] = set()
self.reports = (
("RP0401", "External dependencies", self._report_external_dependencies),
("RP0402", "Modules dependencies graph", self._report_dependencies_graph),
Expand Down Expand Up @@ -478,8 +480,8 @@ def leave_module(self, node: nodes.Module) -> None:
std_imports, ext_imports, loc_imports = self._check_imports_order(node)

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

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

# handle dependencies
dependencies_stat: Dict[str, Set[str]] = self.linter.stats.dependencies
dependencies_stat: dict[str, set[str]] = self.linter.stats.dependencies
importedmodnames = dependencies_stat.setdefault(importedmodname, set())
if context_name not in importedmodnames:
importedmodnames.add(context_name)
Expand All @@ -797,9 +799,7 @@ def _check_preferred_module(self, node, mod_path):
args=(self.preferred_modules[mod_path], mod_path),
)

def _check_import_as_rename(
self, node: Union[nodes.Import, nodes.ImportFrom]
) -> None:
def _check_import_as_rename(self, node: nodes.Import | nodes.ImportFrom) -> None:
names = node.names
for name in names:
if not all(name):
Expand Down Expand Up @@ -935,5 +935,5 @@ def _check_toplevel(self, node):
)


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(ImportsChecker(linter))
Loading