From 7d2584251552283bf95893019e74dad0390dc65c Mon Sep 17 00:00:00 2001 From: Pierre Sassoulas Date: Mon, 27 Dec 2021 21:30:34 +0100 Subject: Add typing and uniformize the checker registering in Pylinter (#5558) Remove verbose docstring in code, keep them in example and doc Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com> --- doc/how_tos/custom_checkers.rst | 14 +++++++- doc/how_tos/plugins.rst | 28 ++++++++++++++-- doc/how_tos/transform_plugins.rst | 13 ++++++-- examples/custom.py | 12 ++++--- examples/custom_raw.py | 12 +++++-- examples/deprecation_checker.py | 12 +++---- pylint/checkers/async.py | 7 ++-- pylint/checkers/base.py | 8 +++-- pylint/checkers/classes/__init__.py | 7 ++-- pylint/checkers/design_analysis.py | 8 +++-- pylint/checkers/ellipsis_checker.py | 9 ++++-- pylint/checkers/exceptions.py | 8 +++-- pylint/checkers/format.py | 9 ++++-- pylint/checkers/imports.py | 11 ++++--- pylint/checkers/logging.py | 8 +++-- pylint/checkers/misc.py | 8 +++-- pylint/checkers/newstyle.py | 8 +++-- pylint/checkers/raw_metrics.py | 8 +++-- pylint/checkers/refactoring/__init__.py | 8 +++-- pylint/checkers/similar.py | 7 ++-- pylint/checkers/spelling.py | 8 +++-- pylint/checkers/stdlib.py | 11 ++++--- pylint/checkers/strings.py | 8 +++-- pylint/checkers/threading_checker.py | 8 +++-- pylint/checkers/typecheck.py | 18 +++++++++-- pylint/checkers/unsupported_version.py | 9 ++++-- pylint/checkers/variables.py | 8 +++-- pylint/extensions/bad_builtin.py | 12 +++---- pylint/extensions/broad_try_clause.py | 8 +++-- pylint/extensions/check_docs.py | 9 +++--- pylint/extensions/check_elif.py | 12 +++---- pylint/extensions/code_style.py | 10 +++--- pylint/extensions/comparetozero.py | 8 +++-- pylint/extensions/comparison_placement.py | 8 +++-- pylint/extensions/confusing_elif.py | 13 ++++---- pylint/extensions/consider_ternary_expression.py | 12 +++---- pylint/extensions/docparams.py | 15 +++------ pylint/extensions/docstyle.py | 11 +++---- pylint/extensions/empty_comment.py | 7 +++- pylint/extensions/emptystring.py | 8 +++-- pylint/extensions/for_any_all.py | 4 --- pylint/extensions/mccabe.py | 12 +++---- pylint/extensions/overlapping_exceptions.py | 8 +++-- pylint/extensions/redefined_variable_type.py | 12 +++---- pylint/extensions/set_membership.py | 10 ++++-- pylint/extensions/typing.py | 10 +++--- pylint/extensions/while_used.py | 12 +++---- pylint/lint/pylinter.py | 6 +--- pylint/reporters/json_reporter.py | 1 - pylint/reporters/reports_handler_mix_in.py | 41 ++++++++++++++---------- pylint/reporters/text.py | 1 - tests/checkers/unittest_similar.py | 2 -- tests/regrtest_data/dummy_plugin/dummy_plugin.py | 2 +- 53 files changed, 328 insertions(+), 201 deletions(-) diff --git a/doc/how_tos/custom_checkers.rst b/doc/how_tos/custom_checkers.rst index 0f6ff6062..30c70d63a 100644 --- a/doc/how_tos/custom_checkers.rst +++ b/doc/how_tos/custom_checkers.rst @@ -201,7 +201,19 @@ Add the ``register`` function to the top level of the file. .. code-block:: python - def register(linter): + from typing import TYPE_CHECKING + + import astroid + + if TYPE_CHECKING: + from pylint.lint import PyLinter + + + def register(linter: "PyLinter") -> None: + """This required method auto registers the checker during initialization. + + :param linter: The linter to register the checker to. + """ linter.register_checker(UniqueReturnChecker(linter)) We are now ready to debug and test our checker! diff --git a/doc/how_tos/plugins.rst b/doc/how_tos/plugins.rst index a68bd22f8..bc2c0f14c 100644 --- a/doc/how_tos/plugins.rst +++ b/doc/how_tos/plugins.rst @@ -25,7 +25,19 @@ So a basic hello-world plugin can be implemented as: .. sourcecode:: python # Inside hello_plugin.py - def register(linter): + from typing import TYPE_CHECKING + + import astroid + + if TYPE_CHECKING: + from pylint.lint import PyLinter + + + def register(linter: "PyLinter") -> None: + """This required method auto registers the checker during initialization. + + :param linter: The linter to register the checker to. + """ print('Hello world') @@ -43,7 +55,19 @@ We can extend hello-world plugin to ignore some specific names using .. sourcecode:: python # Inside hello_plugin.py - def register(linter): + from typing import TYPE_CHECKING + + import astroid + + if TYPE_CHECKING: + from pylint.lint import PyLinter + + + def register(linter: "PyLinter") -> None: + """This required method auto registers the checker during initialization. + + :param linter: The linter to register the checker to. + """ print('Hello world') def load_configuration(linter): diff --git a/doc/how_tos/transform_plugins.rst b/doc/how_tos/transform_plugins.rst index 30e057820..031faa0f1 100644 --- a/doc/how_tos/transform_plugins.rst +++ b/doc/how_tos/transform_plugins.rst @@ -66,10 +66,19 @@ Module, Class, Function etc. In our case we need to transform a class. It can be .. sourcecode:: python + from typing import TYPE_CHECKING + import astroid - def register(linter): - # Needed for registering the plugin. + if TYPE_CHECKING: + from pylint.lint import PyLinter + + + def register(linter: "PyLinter") -> None: + """This required method auto registers the checker during initialization. + + :param linter: The linter to register the checker to. + """ pass def transform(cls): diff --git a/examples/custom.py b/examples/custom.py index c7429f629..695f77d20 100644 --- a/examples/custom.py +++ b/examples/custom.py @@ -1,11 +1,16 @@ +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter -# This is our checker class. # Checkers should always inherit from `BaseChecker`. + + class MyAstroidChecker(BaseChecker): """Add class member attributes to the class local's dictionary.""" @@ -60,10 +65,9 @@ class MyAstroidChecker(BaseChecker): in_class.locals[param.name] = node -def register(linter): - """This required method auto registers the checker. +def register(linter: "PyLinter") -> None: + """This required method auto registers the checker during initialization. :param linter: The linter to register the checker to. - :type linter: pylint.lint.PyLinter """ linter.register_checker(MyAstroidChecker(linter)) diff --git a/examples/custom_raw.py b/examples/custom_raw.py index 5f747869f..045f22ff4 100644 --- a/examples/custom_raw.py +++ b/examples/custom_raw.py @@ -1,8 +1,13 @@ +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.interfaces import IRawChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class MyRawChecker(BaseChecker): """check for line continuations with '\' instead of using triple @@ -35,6 +40,9 @@ class MyRawChecker(BaseChecker): self.add_message("backslash-line-continuation", line=lineno) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: + """This required method auto registers the checker during initialization. + + :param linter: The linter to register the checker to. + """ linter.register_checker(MyRawChecker(linter)) diff --git a/examples/deprecation_checker.py b/examples/deprecation_checker.py index 93910b724..d3dca4e07 100644 --- a/examples/deprecation_checker.py +++ b/examples/deprecation_checker.py @@ -38,11 +38,14 @@ from module mymodule: ------------------------------------------------------------------ Your code has been rated at 2.00/10 (previous run: 2.00/10, +0.00) """ -from typing import Set, Tuple, Union +from typing import TYPE_CHECKING, Set, Tuple, Union from pylint.checkers import BaseChecker, DeprecatedMixin from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class DeprecationChecker(DeprecatedMixin, BaseChecker): """Class implementing deprecation checker.""" @@ -90,10 +93,5 @@ class DeprecationChecker(DeprecatedMixin, BaseChecker): return () -def register(linter): - """This required method auto registers the checker. - - :param linter: The linter to register the checker to. - :type linter: pylint.lint.PyLinter - """ +def register(linter: "PyLinter") -> None: linter.register_checker(DeprecationChecker(linter)) diff --git a/pylint/checkers/async.py b/pylint/checkers/async.py index 9aaead7c4..4a5c6abf2 100644 --- a/pylint/checkers/async.py +++ b/pylint/checkers/async.py @@ -11,6 +11,7 @@ """Checker for anything related to the async protocol (PEP 492).""" import sys +from typing import TYPE_CHECKING import astroid from astroid import nodes @@ -19,6 +20,9 @@ from pylint import checkers, interfaces, utils from pylint.checkers import utils as checker_utils from pylint.checkers.utils import decorated_with +if TYPE_CHECKING: + from pylint.lint import PyLinter + class AsyncChecker(checkers.BaseChecker): __implements__ = interfaces.IAstroidChecker @@ -94,6 +98,5 @@ class AsyncChecker(checkers.BaseChecker): ) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(AsyncChecker(linter)) diff --git a/pylint/checkers/base.py b/pylint/checkers/base.py index 652330f11..39ab5d673 100644 --- a/pylint/checkers/base.py +++ b/pylint/checkers/base.py @@ -73,7 +73,7 @@ import collections import itertools import re import sys -from typing import Any, Dict, Iterator, Optional, Pattern, cast +from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional, Pattern, cast import astroid from astroid import nodes @@ -91,6 +91,9 @@ from pylint.reporters.ureports import nodes as reporter_nodes from pylint.utils import LinterStats from pylint.utils.utils import get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + if sys.version_info >= (3, 8): from typing import Literal else: @@ -2585,8 +2588,7 @@ class ComparisonChecker(_BasicChecker): self.add_message("unidiomatic-typecheck", node=node) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(BasicErrorChecker(linter)) linter.register_checker(BasicChecker(linter)) linter.register_checker(NameChecker(linter)) diff --git a/pylint/checkers/classes/__init__.py b/pylint/checkers/classes/__init__.py index e46eb583d..2b0e595e6 100644 --- a/pylint/checkers/classes/__init__.py +++ b/pylint/checkers/classes/__init__.py @@ -1,12 +1,15 @@ # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE +from typing import TYPE_CHECKING from pylint.checkers.classes.class_checker import ClassChecker from pylint.checkers.classes.special_methods_checker import SpecialMethodsChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter -def register(linter): - """required method to auto register this checker""" + +def register(linter: "PyLinter") -> None: linter.register_checker(ClassChecker(linter)) linter.register_checker(SpecialMethodsChecker(linter)) diff --git a/pylint/checkers/design_analysis.py b/pylint/checkers/design_analysis.py index 8a2623486..ec518e857 100644 --- a/pylint/checkers/design_analysis.py +++ b/pylint/checkers/design_analysis.py @@ -32,7 +32,7 @@ import re from collections import defaultdict -from typing import FrozenSet, Iterator, List, Set, cast +from typing import TYPE_CHECKING, FrozenSet, Iterator, List, Set, cast import astroid from astroid import nodes @@ -42,6 +42,9 @@ from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + MSGS = { # pylint: disable=consider-using-namedtuple-or-dataclass "R0901": ( "Too many ancestors (%s/%s)", @@ -662,6 +665,5 @@ class MisdesignChecker(BaseChecker): self._branches[node.scope()] += branchesnum -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(MisdesignChecker(linter)) diff --git a/pylint/checkers/ellipsis_checker.py b/pylint/checkers/ellipsis_checker.py index ea7a260ec..e5d4c4ecd 100644 --- a/pylint/checkers/ellipsis_checker.py +++ b/pylint/checkers/ellipsis_checker.py @@ -1,11 +1,15 @@ """Ellipsis checker for Python code """ +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter + +if TYPE_CHECKING: + from pylint.lint import PyLinter class EllipsisChecker(BaseChecker): @@ -45,6 +49,5 @@ class EllipsisChecker(BaseChecker): self.add_message("unnecessary-ellipsis", node=node) -def register(linter: PyLinter) -> None: - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(EllipsisChecker(linter)) diff --git a/pylint/checkers/exceptions.py b/pylint/checkers/exceptions.py index b9b6ceb04..0d60b0a39 100644 --- a/pylint/checkers/exceptions.py +++ b/pylint/checkers/exceptions.py @@ -36,7 +36,7 @@ """Checks for various exception related errors.""" import builtins import inspect -from typing import Any, List, Optional +from typing import TYPE_CHECKING, Any, List, Optional import astroid from astroid import nodes, objects @@ -44,6 +44,9 @@ from astroid import nodes, objects from pylint import checkers, interfaces from pylint.checkers import utils +if TYPE_CHECKING: + from pylint.lint import PyLinter + def _builtin_exceptions(): def predicate(obj): @@ -571,6 +574,5 @@ class ExceptionsChecker(checkers.BaseChecker): exceptions_classes += [exc for _, exc in exceptions] -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(ExceptionsChecker(linter)) diff --git a/pylint/checkers/format.py b/pylint/checkers/format.py index 0cee7b90b..17a50911c 100644 --- a/pylint/checkers/format.py +++ b/pylint/checkers/format.py @@ -56,7 +56,7 @@ Some parts of the process_token method is based from The Tab Nanny std module. import tokenize from functools import reduce -from typing import List +from typing import TYPE_CHECKING, List from astroid import nodes @@ -71,6 +71,10 @@ from pylint.constants import WarningScope from pylint.interfaces import IAstroidChecker, IRawChecker, ITokenChecker from pylint.utils.pragma_parser import OPTION_PO, PragmaParserError, parse_pragma +if TYPE_CHECKING: + from pylint.lint import PyLinter + + _ASYNC_TOKEN = "async" _KEYWORD_TOKENS = [ "assert", @@ -819,6 +823,5 @@ class FormatChecker(BaseTokenChecker): ) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(FormatChecker(linter)) diff --git a/pylint/checkers/imports.py b/pylint/checkers/imports.py index ddec800e0..528f7d80c 100644 --- a/pylint/checkers/imports.py +++ b/pylint/checkers/imports.py @@ -52,7 +52,7 @@ import copy import os import sys from distutils import sysconfig -from typing import Any, Dict, List, Optional, Set, Tuple, Union +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Union import astroid from astroid import nodes @@ -69,10 +69,12 @@ from pylint.checkers.utils import ( from pylint.exceptions import EmptyReportError from pylint.graph import DotBackend, get_cycles from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter from pylint.reporters.ureports.nodes import Paragraph, Section, VerbatimText from pylint.utils import IsortDriver, get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + def _qualified_names(modname): """Split the names of the given module into subparts @@ -426,7 +428,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker): ) def __init__( - self, linter: Optional[PyLinter] = None + self, linter: Optional["PyLinter"] = None ): # pylint: disable=super-init-not-called # See https://github.com/PyCQA/pylint/issues/4941 BaseChecker.__init__(self, linter) self.import_graph: collections.defaultdict = collections.defaultdict(set) @@ -1018,6 +1020,5 @@ class ImportsChecker(DeprecatedMixin, BaseChecker): ) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(ImportsChecker(linter)) diff --git a/pylint/checkers/logging.py b/pylint/checkers/logging.py index 242c5e800..19e04c7d1 100644 --- a/pylint/checkers/logging.py +++ b/pylint/checkers/logging.py @@ -26,7 +26,7 @@ """checker for use of Python logging """ import string -from typing import Set +from typing import TYPE_CHECKING, Set import astroid from astroid import nodes @@ -35,6 +35,9 @@ from pylint import checkers, interfaces from pylint.checkers import utils from pylint.checkers.utils import check_messages, infer_all +if TYPE_CHECKING: + from pylint.lint import PyLinter + MSGS = { # pylint: disable=consider-using-namedtuple-or-dataclass "W1201": ( "Use %s formatting in logging functions", @@ -401,6 +404,5 @@ def _count_supplied_tokens(args): return sum(1 for arg in args if not isinstance(arg, nodes.Keyword)) -def register(linter): - """Required method to auto-register this checker.""" +def register(linter: "PyLinter") -> None: linter.register_checker(LoggingChecker(linter)) diff --git a/pylint/checkers/misc.py b/pylint/checkers/misc.py index 8090679e8..4eb52336d 100644 --- a/pylint/checkers/misc.py +++ b/pylint/checkers/misc.py @@ -29,7 +29,7 @@ import re import tokenize -from typing import List, Optional +from typing import TYPE_CHECKING, List, Optional from astroid import nodes @@ -38,6 +38,9 @@ from pylint.interfaces import IRawChecker, ITokenChecker from pylint.typing import ManagedMessage from pylint.utils.pragma_parser import OPTION_PO, PragmaParserError, parse_pragma +if TYPE_CHECKING: + from pylint.lint import PyLinter + class ByIdManagedMessagesChecker(BaseChecker): @@ -195,7 +198,6 @@ class EncodingChecker(BaseChecker): ) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(EncodingChecker(linter)) linter.register_checker(ByIdManagedMessagesChecker(linter)) diff --git a/pylint/checkers/newstyle.py b/pylint/checkers/newstyle.py index 624f60bdd..b19a5c7ef 100644 --- a/pylint/checkers/newstyle.py +++ b/pylint/checkers/newstyle.py @@ -22,6 +22,8 @@ """check for new / old style related problems """ +from typing import TYPE_CHECKING + import astroid from astroid import nodes @@ -29,6 +31,9 @@ from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages, has_known_bases, node_frame_class from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + MSGS = { "E1003": ( "Bad first argument %r given to super()", @@ -132,6 +137,5 @@ class NewStyleConflictChecker(BaseChecker): visit_asyncfunctiondef = visit_functiondef -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(NewStyleConflictChecker(linter)) diff --git a/pylint/checkers/raw_metrics.py b/pylint/checkers/raw_metrics.py index dc49834ef..379665eac 100644 --- a/pylint/checkers/raw_metrics.py +++ b/pylint/checkers/raw_metrics.py @@ -18,7 +18,7 @@ import sys import tokenize -from typing import Any, Optional, cast +from typing import TYPE_CHECKING, Any, Optional, cast from pylint.checkers import BaseTokenChecker from pylint.interfaces import ITokenChecker @@ -30,6 +30,9 @@ if sys.version_info >= (3, 8): else: from typing_extensions import Literal +if TYPE_CHECKING: + from pylint.lint import PyLinter + def report_raw_stats( sect, @@ -122,6 +125,5 @@ def get_type(tokens, start_index): return i, pos[0] - start[0] + 1, line_type -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(RawMetricsChecker(linter)) diff --git a/pylint/checkers/refactoring/__init__.py b/pylint/checkers/refactoring/__init__.py index c43b6c364..8c873c698 100644 --- a/pylint/checkers/refactoring/__init__.py +++ b/pylint/checkers/refactoring/__init__.py @@ -38,6 +38,8 @@ """Looks for code which can be refactored.""" +from typing import TYPE_CHECKING + from pylint.checkers.refactoring.implicit_booleaness_checker import ( ImplicitBooleanessChecker, ) @@ -45,6 +47,9 @@ from pylint.checkers.refactoring.not_checker import NotChecker from pylint.checkers.refactoring.recommendation_checker import RecommendationChecker from pylint.checkers.refactoring.refactoring_checker import RefactoringChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + __all__ = [ "ImplicitBooleanessChecker", "NotChecker", @@ -53,8 +58,7 @@ __all__ = [ ] -def register(linter): - """Required method to auto register this checker.""" +def register(linter: "PyLinter") -> None: linter.register_checker(RefactoringChecker(linter)) linter.register_checker(NotChecker(linter)) linter.register_checker(RecommendationChecker(linter)) diff --git a/pylint/checkers/similar.py b/pylint/checkers/similar.py index cadee9f70..51ec27c0b 100644 --- a/pylint/checkers/similar.py +++ b/pylint/checkers/similar.py @@ -52,6 +52,7 @@ from getopt import getopt from io import BufferedIOBase, BufferedReader, BytesIO from itertools import chain, groupby from typing import ( + TYPE_CHECKING, Any, Dict, FrozenSet, @@ -75,6 +76,9 @@ from pylint.interfaces import IRawChecker from pylint.reporters.ureports.nodes import Table from pylint.utils import LinterStats, decoding_stream +if TYPE_CHECKING: + from pylint.lint import PyLinter + DEFAULT_MIN_SIMILARITY_LINE = 4 REGEX_FOR_LINES_WITH_CONTENT = re.compile(r".*\w+") @@ -879,8 +883,7 @@ class SimilarChecker(BaseChecker, Similar, MapReduceMixin): recombined.close() -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(SimilarChecker(linter)) diff --git a/pylint/checkers/spelling.py b/pylint/checkers/spelling.py index ad6847478..012c396de 100644 --- a/pylint/checkers/spelling.py +++ b/pylint/checkers/spelling.py @@ -33,7 +33,7 @@ import os import re import tokenize -from typing import Pattern +from typing import TYPE_CHECKING, Pattern from astroid import nodes @@ -41,6 +41,9 @@ from pylint.checkers import BaseTokenChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker, ITokenChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + try: import enchant from enchant.tokenize import ( @@ -470,6 +473,5 @@ class SpellingChecker(BaseTokenChecker): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(SpellingChecker(linter)) diff --git a/pylint/checkers/stdlib.py b/pylint/checkers/stdlib.py index f77f7a2b3..7093bb0da 100644 --- a/pylint/checkers/stdlib.py +++ b/pylint/checkers/stdlib.py @@ -39,14 +39,16 @@ import sys from collections.abc import Iterable -from typing import Any, Dict, Optional, Set +from typing import TYPE_CHECKING, Any, Dict, Optional, Set import astroid from astroid import nodes from pylint.checkers import BaseChecker, DeprecatedMixin, utils from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter + +if TYPE_CHECKING: + from pylint.lint import PyLinter OPEN_FILES_MODE = ("open", "file") OPEN_FILES_ENCODING = ("open", "read_text", "write_text") @@ -447,7 +449,7 @@ class StdlibChecker(DeprecatedMixin, BaseChecker): } def __init__( - self, linter: Optional[PyLinter] = None + self, linter: Optional["PyLinter"] = None ): # pylint: disable=super-init-not-called # See https://github.com/PyCQA/pylint/issues/4941 BaseChecker.__init__(self, linter) self._deprecated_methods: Set[Any] = set() @@ -723,6 +725,5 @@ class StdlibChecker(DeprecatedMixin, BaseChecker): return self._deprecated_decorators -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(StdlibChecker(linter)) diff --git a/pylint/checkers/strings.py b/pylint/checkers/strings.py index 064902b5d..e4dcfc831 100644 --- a/pylint/checkers/strings.py +++ b/pylint/checkers/strings.py @@ -41,7 +41,7 @@ import collections import numbers import re import tokenize -from typing import Counter, Iterable +from typing import TYPE_CHECKING, Counter, Iterable import astroid from astroid import nodes @@ -50,6 +50,9 @@ from pylint.checkers import BaseChecker, BaseTokenChecker, utils from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker, IRawChecker, ITokenChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + _AST_NODE_STR_TYPES = ("__builtin__.unicode", "__builtin__.str", "builtins.str") # Prefixes for both strings and bytes literals per # https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals @@ -925,8 +928,7 @@ class StringConstantChecker(BaseTokenChecker): ) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(StringFormatChecker(linter)) linter.register_checker(StringConstantChecker(linter)) diff --git a/pylint/checkers/threading_checker.py b/pylint/checkers/threading_checker.py index b7ba91d41..cedf46a9e 100644 --- a/pylint/checkers/threading_checker.py +++ b/pylint/checkers/threading_checker.py @@ -1,12 +1,17 @@ # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE +from typing import TYPE_CHECKING + from astroid import nodes from pylint import interfaces from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages, safe_infer +if TYPE_CHECKING: + from pylint.lint import PyLinter + class ThreadingChecker(BaseChecker): """Checks for threading module @@ -50,6 +55,5 @@ class ThreadingChecker(BaseChecker): self.add_message("useless-with-lock", node=node, args=qname) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(ThreadingChecker(linter)) diff --git a/pylint/checkers/typecheck.py b/pylint/checkers/typecheck.py index b4f224c06..a2239469a 100644 --- a/pylint/checkers/typecheck.py +++ b/pylint/checkers/typecheck.py @@ -69,7 +69,17 @@ import types from collections import deque from collections.abc import Sequence from functools import singledispatch -from typing import Any, Callable, Iterator, List, Optional, Pattern, Tuple, Union +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Iterator, + List, + Optional, + Pattern, + Tuple, + Union, +) import astroid import astroid.exceptions @@ -100,6 +110,9 @@ from pylint.checkers.utils import ( from pylint.interfaces import INFERENCE, IAstroidChecker from pylint.utils import get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + CallableObjects = Union[ bases.BoundMethod, bases.UnboundMethod, @@ -2090,7 +2103,6 @@ class IterableChecker(BaseChecker): self.add_message("await-outside-async", node=node) -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(TypeChecker(linter)) linter.register_checker(IterableChecker(linter)) diff --git a/pylint/checkers/unsupported_version.py b/pylint/checkers/unsupported_version.py index 52e0b5c75..64078aa68 100644 --- a/pylint/checkers/unsupported_version.py +++ b/pylint/checkers/unsupported_version.py @@ -10,6 +10,8 @@ indicated by the py-version setting. """ +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker @@ -19,9 +21,11 @@ from pylint.checkers.utils import ( uninferable_final_decorators, ) from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter from pylint.utils import get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + class UnsupportedVersionChecker(BaseChecker): """Checker for features that are not supported by all python versions @@ -80,6 +84,5 @@ class UnsupportedVersionChecker(BaseChecker): ) -def register(linter: PyLinter) -> None: - """Required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(UnsupportedVersionChecker(linter)) diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index a32099dfd..8bfdc197e 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -63,7 +63,7 @@ import re import sys from enum import Enum from functools import lru_cache -from typing import Any, DefaultDict, List, Optional, Set, Tuple, Union +from typing import TYPE_CHECKING, Any, DefaultDict, List, Optional, Set, Tuple, Union import astroid from astroid import nodes @@ -74,6 +74,9 @@ from pylint.constants import PY39_PLUS from pylint.interfaces import HIGH, INFERENCE, INFERENCE_FAILURE, IAstroidChecker from pylint.utils import get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + if sys.version_info >= (3, 8): from typing import Literal else: @@ -2527,6 +2530,5 @@ class VariablesChecker(BaseChecker): return consumed -def register(linter): - """required method to auto register this checker""" +def register(linter: "PyLinter") -> None: linter.register_checker(VariablesChecker(linter)) diff --git a/pylint/extensions/bad_builtin.py b/pylint/extensions/bad_builtin.py index b90ede111..197bf231b 100644 --- a/pylint/extensions/bad_builtin.py +++ b/pylint/extensions/bad_builtin.py @@ -11,12 +11,17 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE """Checker for deprecated builtins.""" +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + BAD_FUNCTIONS = ["map", "filter"] # Some hints regarding the use of bad builtins. BUILTIN_HINTS = {"map": "Using a list comprehension can be clearer."} @@ -64,10 +69,5 @@ class BadBuiltinChecker(BaseChecker): self.add_message("bad-builtin", node=node, args=args) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(BadBuiltinChecker(linter)) diff --git a/pylint/extensions/broad_try_clause.py b/pylint/extensions/broad_try_clause.py index b460850c2..a45dc5fe6 100644 --- a/pylint/extensions/broad_try_clause.py +++ b/pylint/extensions/broad_try_clause.py @@ -10,12 +10,15 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE """Looks for try/except statements with too much code in the try clause.""" -from typing import Union +from typing import TYPE_CHECKING, Union from astroid import nodes from pylint import checkers, interfaces +if TYPE_CHECKING: + from pylint.lint import PyLinter + class BroadTryClauseChecker(checkers.BaseChecker): """Checks for try clauses with too many lines. @@ -72,6 +75,5 @@ class BroadTryClauseChecker(checkers.BaseChecker): self.visit_tryexcept(node) -def register(linter): - """Required method to auto register this checker.""" +def register(linter: "PyLinter") -> None: linter.register_checker(BroadTryClauseChecker(linter)) diff --git a/pylint/extensions/check_docs.py b/pylint/extensions/check_docs.py index 96ea4311f..141f51298 100644 --- a/pylint/extensions/check_docs.py +++ b/pylint/extensions/check_docs.py @@ -9,16 +9,15 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE import warnings +from typing import TYPE_CHECKING from pylint.extensions import docparams +if TYPE_CHECKING: + from pylint.lint import PyLinter -def register(linter): - """Required method to auto register this checker. - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: warnings.warn( "This plugin is deprecated, use pylint.extensions.docparams instead.", DeprecationWarning, diff --git a/pylint/extensions/check_elif.py b/pylint/extensions/check_elif.py index f70b43684..b4658577e 100644 --- a/pylint/extensions/check_elif.py +++ b/pylint/extensions/check_elif.py @@ -12,12 +12,17 @@ # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseTokenChecker from pylint.checkers.utils import check_messages from pylint.interfaces import HIGH, IAstroidChecker, ITokenChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class ElseifUsedChecker(BaseTokenChecker): """Checks for use of "else if" when an "elif" could be used""" @@ -62,10 +67,5 @@ class ElseifUsedChecker(BaseTokenChecker): self.add_message("else-if-used", node=node, confidence=HIGH) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(ElseifUsedChecker(linter)) diff --git a/pylint/extensions/code_style.py b/pylint/extensions/code_style.py index 332ffaa92..7082c991c 100644 --- a/pylint/extensions/code_style.py +++ b/pylint/extensions/code_style.py @@ -1,14 +1,16 @@ import sys -from typing import List, Optional, Set, Tuple, Type, Union, cast +from typing import TYPE_CHECKING, List, Optional, Set, Tuple, Type, Union, cast from astroid import nodes from pylint.checkers import BaseChecker, utils from pylint.checkers.utils import check_messages, safe_infer from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter from pylint.utils.utils import get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + if sys.version_info >= (3, 10): from typing import TypeGuard else: @@ -72,7 +74,7 @@ class CodeStyleChecker(BaseChecker): ), ) - def __init__(self, linter: PyLinter) -> None: + def __init__(self, linter: "PyLinter") -> None: """Initialize checker instance.""" super().__init__(linter=linter) @@ -303,5 +305,5 @@ class CodeStyleChecker(BaseChecker): return False -def register(linter: PyLinter) -> None: +def register(linter: "PyLinter") -> None: linter.register_checker(CodeStyleChecker(linter)) diff --git a/pylint/extensions/comparetozero.py b/pylint/extensions/comparetozero.py index e543f1ccf..592e15a5b 100644 --- a/pylint/extensions/comparetozero.py +++ b/pylint/extensions/comparetozero.py @@ -13,7 +13,7 @@ """Looks for comparisons to zero.""" import itertools -from typing import Any, Iterable +from typing import TYPE_CHECKING, Any, Iterable import astroid from astroid import nodes @@ -21,6 +21,9 @@ from astroid import nodes from pylint import checkers, interfaces from pylint.checkers import utils +if TYPE_CHECKING: + from pylint.lint import PyLinter + def _is_constant_zero(node): return isinstance(node, astroid.Const) and node.value == 0 @@ -77,6 +80,5 @@ class CompareToZeroChecker(checkers.BaseChecker): self.add_message("compare-to-zero", node=node) -def register(linter): - """Required method to auto register this checker.""" +def register(linter: "PyLinter") -> None: linter.register_checker(CompareToZeroChecker(linter)) diff --git a/pylint/extensions/comparison_placement.py b/pylint/extensions/comparison_placement.py index 64c8dee5e..c4a5cffcb 100644 --- a/pylint/extensions/comparison_placement.py +++ b/pylint/extensions/comparison_placement.py @@ -7,11 +7,16 @@ See https://en.wikipedia.org/wiki/Yoda_conditions """ +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker, utils from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + REVERSED_COMPS = {"<": ">", "<=": ">=", ">": "<", ">=": "<="} COMPARISON_OPERATORS = frozenset(("==", "!=", "<", ">", "<=", ">=")) @@ -62,6 +67,5 @@ class MisplacedComparisonConstantChecker(BaseChecker): self._check_misplaced_constant(node, left, right, operator) -def register(linter): - """Required method to auto register this checker.""" +def register(linter: "PyLinter") -> None: linter.register_checker(MisplacedComparisonConstantChecker(linter)) diff --git a/pylint/extensions/confusing_elif.py b/pylint/extensions/confusing_elif.py index 7f81fceaa..99588d0b8 100644 --- a/pylint/extensions/confusing_elif.py +++ b/pylint/extensions/confusing_elif.py @@ -7,12 +7,16 @@ # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter + +if TYPE_CHECKING: + from pylint.lint import PyLinter class ConfusingConsecutiveElifChecker(BaseChecker): @@ -50,10 +54,5 @@ class ConfusingConsecutiveElifChecker(BaseChecker): return False -def register(linter: PyLinter): - """This required method auto registers the checker. - - :param linter: The linter to register the checker to. - :type linter: pylint.lint.PyLinter - """ +def register(linter: "PyLinter") -> None: linter.register_checker(ConfusingConsecutiveElifChecker(linter)) diff --git a/pylint/extensions/consider_ternary_expression.py b/pylint/extensions/consider_ternary_expression.py index 3e3e87c6b..6dabe3613 100644 --- a/pylint/extensions/consider_ternary_expression.py +++ b/pylint/extensions/consider_ternary_expression.py @@ -1,10 +1,15 @@ """Check for if / assign blocks that can be rewritten with if-expressions.""" +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class ConsiderTernaryExpressionChecker(BaseChecker): @@ -44,10 +49,5 @@ class ConsiderTernaryExpressionChecker(BaseChecker): self.add_message("consider-ternary-expression", node=node) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(ConsiderTernaryExpressionChecker(linter)) diff --git a/pylint/extensions/docparams.py b/pylint/extensions/docparams.py index 4fadf9458..8a29a947d 100644 --- a/pylint/extensions/docparams.py +++ b/pylint/extensions/docparams.py @@ -27,7 +27,7 @@ """Pylint plugin for checking in Sphinx, Google, or Numpy style docstrings """ import re -from typing import Optional +from typing import TYPE_CHECKING, Optional import astroid from astroid import nodes @@ -39,6 +39,9 @@ from pylint.extensions._check_docs_utils import Docstring from pylint.interfaces import IAstroidChecker from pylint.utils import get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + class DocstringParameterChecker(BaseChecker): """Checker for Sphinx, Google, or Numpy style docstrings @@ -59,9 +62,6 @@ class DocstringParameterChecker(BaseChecker): load-plugins=pylint.extensions.docparams to the ``MASTER`` section of your ``.pylintrc``. - - :param linter: linter object - :type linter: :class:`pylint.lint.PyLinter` """ __implements__ = IAstroidChecker @@ -665,10 +665,5 @@ class DocstringParameterChecker(BaseChecker): ) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(DocstringParameterChecker(linter)) diff --git a/pylint/extensions/docstyle.py b/pylint/extensions/docstyle.py index 7866312b2..c0fed60fe 100644 --- a/pylint/extensions/docstyle.py +++ b/pylint/extensions/docstyle.py @@ -11,6 +11,7 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE import linecache +from typing import TYPE_CHECKING from astroid import nodes @@ -18,6 +19,9 @@ from pylint import checkers from pylint.checkers.utils import check_messages from pylint.interfaces import HIGH, IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class DocStringStyleChecker(checkers.BaseChecker): """Checks format of docstrings based on PEP 0257""" @@ -86,10 +90,5 @@ class DocStringStyleChecker(checkers.BaseChecker): ) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(DocStringStyleChecker(linter)) diff --git a/pylint/extensions/empty_comment.py b/pylint/extensions/empty_comment.py index 7b9841678..c52540308 100644 --- a/pylint/extensions/empty_comment.py +++ b/pylint/extensions/empty_comment.py @@ -1,8 +1,13 @@ +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.interfaces import IRawChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + def is_line_commented(line): """Checks if a `# symbol that is not part of a string was found in line""" @@ -54,5 +59,5 @@ class CommentChecker(BaseChecker): self.add_message("empty-comment", line=line_num + 1) -def register(linter): +def register(linter: "PyLinter") -> None: linter.register_checker(CommentChecker(linter)) diff --git a/pylint/extensions/emptystring.py b/pylint/extensions/emptystring.py index 4e466aca4..15bdd1e58 100644 --- a/pylint/extensions/emptystring.py +++ b/pylint/extensions/emptystring.py @@ -13,13 +13,16 @@ """Looks for comparisons to empty string.""" import itertools -from typing import Any, Iterable +from typing import TYPE_CHECKING, Any, Iterable from astroid import nodes from pylint import checkers, interfaces from pylint.checkers import utils +if TYPE_CHECKING: + from pylint.lint import PyLinter + class CompareToEmptyStringChecker(checkers.BaseChecker): """Checks for comparisons to empty string. @@ -72,6 +75,5 @@ class CompareToEmptyStringChecker(checkers.BaseChecker): self.add_message("compare-to-empty-string", node=node) -def register(linter): - """Required method to auto register this checker.""" +def register(linter: "PyLinter") -> None: linter.register_checker(CompareToEmptyStringChecker(linter)) diff --git a/pylint/extensions/for_any_all.py b/pylint/extensions/for_any_all.py index 2086fa4b1..915fae8a3 100644 --- a/pylint/extensions/for_any_all.py +++ b/pylint/extensions/for_any_all.py @@ -66,8 +66,4 @@ class ConsiderUsingAnyOrAllChecker(BaseChecker): def register(linter: "PyLinter") -> None: - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - """ linter.register_checker(ConsiderUsingAnyOrAllChecker(linter)) diff --git a/pylint/extensions/mccabe.py b/pylint/extensions/mccabe.py index 27d246c1e..d4e752f48 100644 --- a/pylint/extensions/mccabe.py +++ b/pylint/extensions/mccabe.py @@ -13,6 +13,8 @@ """Module to add McCabe checker class for pylint. """ +from typing import TYPE_CHECKING + from astroid import nodes from mccabe import PathGraph as Mccabe_PathGraph from mccabe import PathGraphingAstVisitor as Mccabe_PathGraphingAstVisitor @@ -21,6 +23,9 @@ from pylint import checkers from pylint.checkers.utils import check_messages from pylint.interfaces import HIGH, IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class PathGraph(Mccabe_PathGraph): def __init__(self, node): @@ -194,10 +199,5 @@ class McCabeMethodChecker(checkers.BaseChecker): ) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(McCabeMethodChecker(linter)) diff --git a/pylint/extensions/overlapping_exceptions.py b/pylint/extensions/overlapping_exceptions.py index 470582b68..ef6afefea 100644 --- a/pylint/extensions/overlapping_exceptions.py +++ b/pylint/extensions/overlapping_exceptions.py @@ -3,7 +3,7 @@ """Looks for overlapping exceptions.""" -from typing import Any, List, Tuple +from typing import TYPE_CHECKING, Any, List, Tuple import astroid from astroid import nodes @@ -12,6 +12,9 @@ from pylint import checkers, interfaces from pylint.checkers import utils from pylint.checkers.exceptions import _annotated_unpack_infer +if TYPE_CHECKING: + from pylint.lint import PyLinter + class OverlappingExceptionsChecker(checkers.BaseChecker): """Checks for two or more exceptions in the same exception handler @@ -81,6 +84,5 @@ class OverlappingExceptionsChecker(checkers.BaseChecker): handled_in_clause += [(part, exc)] -def register(linter): - """Required method to auto register this checker.""" +def register(linter: "PyLinter") -> None: linter.register_checker(OverlappingExceptionsChecker(linter)) diff --git a/pylint/extensions/redefined_variable_type.py b/pylint/extensions/redefined_variable_type.py index a2b5f2a20..775f7adae 100644 --- a/pylint/extensions/redefined_variable_type.py +++ b/pylint/extensions/redefined_variable_type.py @@ -11,7 +11,7 @@ # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE -from typing import List +from typing import TYPE_CHECKING, List from astroid import nodes @@ -19,6 +19,9 @@ from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages, is_none, node_type from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class MultipleTypesChecker(BaseChecker): """Checks for variable type redefinitions (NoneType excepted) @@ -111,10 +114,5 @@ class MultipleTypesChecker(BaseChecker): ) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(MultipleTypesChecker(linter)) diff --git a/pylint/extensions/set_membership.py b/pylint/extensions/set_membership.py index c63e268b3..6ba5166c5 100644 --- a/pylint/extensions/set_membership.py +++ b/pylint/extensions/set_membership.py @@ -1,9 +1,13 @@ +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter + +if TYPE_CHECKING: + from pylint.lint import PyLinter class SetMembershipChecker(BaseChecker): @@ -21,7 +25,7 @@ class SetMembershipChecker(BaseChecker): ), } - def __init__(self, linter: PyLinter) -> None: + def __init__(self, linter: "PyLinter") -> None: """Initialize checker instance.""" super().__init__(linter=linter) @@ -43,5 +47,5 @@ class SetMembershipChecker(BaseChecker): self.add_message("use-set-for-membership", node=comparator) -def register(linter: PyLinter) -> None: +def register(linter: "PyLinter") -> None: linter.register_checker(SetMembershipChecker(linter)) diff --git a/pylint/extensions/typing.py b/pylint/extensions/typing.py index 79cb18ed3..cc68bc35e 100644 --- a/pylint/extensions/typing.py +++ b/pylint/extensions/typing.py @@ -1,4 +1,4 @@ -from typing import Dict, List, NamedTuple, Set, Union +from typing import TYPE_CHECKING, Dict, List, NamedTuple, Set, Union import astroid.bases from astroid import nodes @@ -10,9 +10,11 @@ from pylint.checkers.utils import ( safe_infer, ) from pylint.interfaces import IAstroidChecker -from pylint.lint import PyLinter from pylint.utils.utils import get_global_option +if TYPE_CHECKING: + from pylint.lint import PyLinter + class TypingAlias(NamedTuple): name: str @@ -132,7 +134,7 @@ class TypingChecker(BaseChecker): or Python 3.7+ with postponed evaluation. """ - def __init__(self, linter: PyLinter) -> None: + def __init__(self, linter: "PyLinter") -> None: """Initialize checker instance.""" super().__init__(linter=linter) self._alias_name_collisions: Set[str] = set() @@ -278,5 +280,5 @@ class TypingChecker(BaseChecker): self._consider_using_alias_msgs.clear() -def register(linter: PyLinter) -> None: +def register(linter: "PyLinter") -> None: linter.register_checker(TypingChecker(linter)) diff --git a/pylint/extensions/while_used.py b/pylint/extensions/while_used.py index 8d05ace90..dc9861bac 100644 --- a/pylint/extensions/while_used.py +++ b/pylint/extensions/while_used.py @@ -1,10 +1,15 @@ """Check for use of while loops.""" +from typing import TYPE_CHECKING + from astroid import nodes from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker +if TYPE_CHECKING: + from pylint.lint import PyLinter + class WhileChecker(BaseChecker): @@ -23,10 +28,5 @@ class WhileChecker(BaseChecker): self.add_message("while-used", node=node) -def register(linter): - """Required method to auto register this checker. - - :param linter: Main interface object for Pylint plugins - :type linter: Pylint object - """ +def register(linter: "PyLinter") -> None: linter.register_checker(WhileChecker(linter)) diff --git a/pylint/lint/pylinter.py b/pylint/lint/pylinter.py index 023455f68..887c9357a 100644 --- a/pylint/lint/pylinter.py +++ b/pylint/lint/pylinter.py @@ -752,10 +752,7 @@ class PyLinter( # checkers manipulation methods ############################################ def register_checker(self, checker: checkers.BaseChecker) -> None: - """register a new checker - - checker is an object implementing IRawChecker or / and IAstroidChecker - """ + """This method auto registers the checker.""" assert checker.priority <= 0, "checker priority can't be >= 0" self._checkers[checker.name].append(checker) for r_id, r_title, r_cb in checker.reports: @@ -764,7 +761,6 @@ class PyLinter( if hasattr(checker, "msgs"): self.msgs_store.register_messages_from_checker(checker) checker.load_defaults() - # Register the checker, but disable all of its messages. if not getattr(checker, "enabled", True): self.disable(checker.name) diff --git a/pylint/reporters/json_reporter.py b/pylint/reporters/json_reporter.py index 84d11d24a..8761979aa 100644 --- a/pylint/reporters/json_reporter.py +++ b/pylint/reporters/json_reporter.py @@ -59,5 +59,4 @@ class JSONReporter(BaseReporter): def register(linter: "PyLinter") -> None: - """Register the reporter classes with the linter.""" linter.register_reporter(JSONReporter) diff --git a/pylint/reporters/reports_handler_mix_in.py b/pylint/reporters/reports_handler_mix_in.py index a71e1bc7b..245d2ded1 100644 --- a/pylint/reporters/reports_handler_mix_in.py +++ b/pylint/reporters/reports_handler_mix_in.py @@ -2,21 +2,30 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE import collections -from typing import TYPE_CHECKING, Callable, DefaultDict, Dict, List, Optional, Tuple +from typing import ( + TYPE_CHECKING, + Callable, + DefaultDict, + Dict, + List, + MutableSequence, + Optional, + Tuple, +) -from pylint import checkers from pylint.exceptions import EmptyReportError from pylint.reporters.ureports.nodes import Section from pylint.utils import LinterStats if TYPE_CHECKING: + from pylint.checkers import BaseChecker from pylint.lint.pylinter import PyLinter -ReportsDict = DefaultDict[checkers.BaseChecker, List[Tuple[str, str, Callable]]] +ReportsDict = DefaultDict["BaseChecker", List[Tuple[str, str, Callable]]] class ReportsHandlerMixIn: - """a mix-in class containing all the reports and stats manipulation + """A mix-in class containing all the reports and stats manipulation related methods for the main lint class """ @@ -24,37 +33,35 @@ class ReportsHandlerMixIn: self._reports: ReportsDict = collections.defaultdict(list) self._reports_state: Dict[str, bool] = {} - def report_order(self) -> List[checkers.BaseChecker]: + def report_order(self) -> MutableSequence["BaseChecker"]: """Return a list of reporters""" return list(self._reports) def register_report( - self, reportid: str, r_title: str, r_cb: Callable, checker: checkers.BaseChecker + self, reportid: str, r_title: str, r_cb: Callable, checker: "BaseChecker" ) -> None: - """register a report + """Register a report - reportid is the unique identifier for the report - r_title the report's title - r_cb the method to call to make the report - checker is the checker defining the report + :param reportid: The unique identifier for the report + :param r_title: The report's title + :param r_cb: The method to call to make the report + :param checker: The checker defining the report """ reportid = reportid.upper() self._reports[checker].append((reportid, r_title, r_cb)) def enable_report(self, reportid: str) -> None: - """disable the report of the given id""" + """Enable the report of the given id""" reportid = reportid.upper() self._reports_state[reportid] = True def disable_report(self, reportid: str) -> None: - """disable the report of the given id""" + """Disable the report of the given id""" reportid = reportid.upper() self._reports_state[reportid] = False def report_is_enabled(self, reportid: str) -> bool: - """return true if the report associated to the given identifier is - enabled - """ + """Is the report associated to the given identifier enabled ?""" return self._reports_state.get(reportid, True) def make_reports( # type: ignore[misc] # ReportsHandlerMixIn is always mixed with PyLinter @@ -62,7 +69,7 @@ class ReportsHandlerMixIn: stats: LinterStats, old_stats: Optional[LinterStats], ) -> Section: - """render registered reports""" + """Render registered reports""" sect = Section("Report", f"{self.stats.statement} statements analysed.") for checker in self.report_order(): for reportid, r_title, r_cb in self._reports[checker]: diff --git a/pylint/reporters/text.py b/pylint/reporters/text.py index 7b6e5e1a1..b69a3a139 100644 --- a/pylint/reporters/text.py +++ b/pylint/reporters/text.py @@ -352,7 +352,6 @@ class ColorizedTextReporter(TextReporter): def register(linter: "PyLinter") -> None: - """Register the reporter classes with the linter.""" linter.register_reporter(TextReporter) linter.register_reporter(ParseableTextReporter) linter.register_reporter(VSTextReporter) diff --git a/tests/checkers/unittest_similar.py b/tests/checkers/unittest_similar.py index a9a13b72a..5caaac794 100644 --- a/tests/checkers/unittest_similar.py +++ b/tests/checkers/unittest_similar.py @@ -396,10 +396,8 @@ def test_no_args() -> None: def test_get_map_data() -> None: """Tests that a SimilarChecker respects the MapReduceMixin interface""" linter = PyLinter(reporter=Reporter()) - # Add a parallel checker to ensure it can map and reduce linter.register_checker(similar.SimilarChecker(linter)) - source_streams = ( str(INPUT / "similar_lines_a.py"), str(INPUT / "similar_lines_b.py"), diff --git a/tests/regrtest_data/dummy_plugin/dummy_plugin.py b/tests/regrtest_data/dummy_plugin/dummy_plugin.py index dd0554f7e..22b0ea391 100644 --- a/tests/regrtest_data/dummy_plugin/dummy_plugin.py +++ b/tests/regrtest_data/dummy_plugin/dummy_plugin.py @@ -26,6 +26,6 @@ class DummyPlugin2(BaseChecker): ) -def register(linter: PyLinter) -> None: +def register(linter: "PyLinter") -> None: linter.register_checker(DummyPlugin1(linter)) linter.register_checker(DummyPlugin2(linter)) -- cgit v1.2.1