summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.pre-commit-config.yaml2
-rwxr-xr-xdoc/exts/pylint_extensions.py2
-rw-r--r--doc/exts/pylint_messages.py6
-rw-r--r--examples/custom_raw.py4
-rw-r--r--pylint/__init__.py8
-rw-r--r--pylint/__pkginfo__.py2
-rw-r--r--pylint/checkers/__init__.py6
-rw-r--r--pylint/checkers/base.py64
-rw-r--r--pylint/checkers/base_checker.py6
-rw-r--r--pylint/checkers/classes/class_checker.py48
-rw-r--r--pylint/checkers/classes/special_methods_checker.py2
-rw-r--r--pylint/checkers/deprecated.py12
-rw-r--r--pylint/checkers/design_analysis.py32
-rw-r--r--pylint/checkers/ellipsis_checker.py2
-rw-r--r--pylint/checkers/exceptions.py4
-rw-r--r--pylint/checkers/format.py18
-rw-r--r--pylint/checkers/imports.py46
-rw-r--r--pylint/checkers/logging.py4
-rw-r--r--pylint/checkers/mapreduce_checker.py6
-rw-r--r--pylint/checkers/misc.py8
-rw-r--r--pylint/checkers/newstyle.py6
-rw-r--r--pylint/checkers/non_ascii_names.py4
-rw-r--r--pylint/checkers/raw_metrics.py10
-rw-r--r--pylint/checkers/refactoring/implicit_booleaness_checker.py2
-rw-r--r--pylint/checkers/refactoring/not_checker.py2
-rw-r--r--pylint/checkers/refactoring/refactoring_checker.py26
-rw-r--r--pylint/checkers/similar.py52
-rw-r--r--pylint/checkers/spelling.py6
-rw-r--r--pylint/checkers/strings.py6
-rw-r--r--pylint/checkers/threading_checker.py2
-rw-r--r--pylint/checkers/typecheck.py20
-rw-r--r--pylint/checkers/unicode.py36
-rw-r--r--pylint/checkers/unsupported_version.py4
-rw-r--r--pylint/checkers/utils.py62
-rw-r--r--pylint/checkers/variables.py70
-rw-r--r--pylint/config/find_default_config_files.py2
-rw-r--r--pylint/config/man_help_formatter.py2
-rw-r--r--pylint/config/option.py2
-rw-r--r--pylint/config/option_manager_mixin.py24
-rw-r--r--pylint/config/options_provider_mixin.py16
-rwxr-xr-xpylint/epylint.py2
-rw-r--r--pylint/exceptions.py12
-rw-r--r--pylint/extensions/__init__.py2
-rw-r--r--pylint/extensions/_check_docs_utils.py10
-rw-r--r--pylint/extensions/check_elif.py6
-rw-r--r--pylint/extensions/comparison_placement.py2
-rw-r--r--pylint/extensions/docparams.py4
-rw-r--r--pylint/extensions/docstyle.py2
-rw-r--r--pylint/extensions/empty_comment.py4
-rw-r--r--pylint/extensions/mccabe.py8
-rw-r--r--pylint/extensions/overlapping_exceptions.py2
-rw-r--r--pylint/extensions/redefined_variable_type.py2
-rw-r--r--pylint/graph.py10
-rw-r--r--pylint/interfaces.py16
-rw-r--r--pylint/lint/__init__.py2
-rw-r--r--pylint/lint/expand_modules.py4
-rw-r--r--pylint/lint/parallel.py4
-rw-r--r--pylint/lint/pylinter.py74
-rw-r--r--pylint/lint/report_functions.py6
-rw-r--r--pylint/lint/run.py32
-rw-r--r--pylint/lint/utils.py2
-rw-r--r--pylint/message/message.py2
-rw-r--r--pylint/message/message_definition.py6
-rw-r--r--pylint/message/message_definition_store.py4
-rw-r--r--pylint/pyreverse/__init__.py2
-rw-r--r--pylint/pyreverse/diadefslib.py44
-rw-r--r--pylint/pyreverse/diagrams.py50
-rw-r--r--pylint/pyreverse/dot_printer.py2
-rw-r--r--pylint/pyreverse/inspector.py28
-rw-r--r--pylint/pyreverse/main.py6
-rw-r--r--pylint/pyreverse/mermaidjs_printer.py8
-rw-r--r--pylint/pyreverse/plantuml_printer.py4
-rw-r--r--pylint/pyreverse/printer.py6
-rw-r--r--pylint/pyreverse/utils.py32
-rw-r--r--pylint/pyreverse/vcg_printer.py4
-rw-r--r--pylint/pyreverse/writer.py20
-rw-r--r--pylint/reporters/__init__.py4
-rw-r--r--pylint/reporters/base_reporter.py14
-rw-r--r--pylint/reporters/collecting_reporter.py2
-rw-r--r--pylint/reporters/json_reporter.py4
-rw-r--r--pylint/reporters/multi_reporter.py12
-rw-r--r--pylint/reporters/reports_handler_mix_in.py10
-rw-r--r--pylint/reporters/text.py26
-rw-r--r--pylint/reporters/ureports/base_writer.py18
-rw-r--r--pylint/reporters/ureports/nodes.py22
-rw-r--r--pylint/reporters/ureports/text_writer.py16
-rw-r--r--pylint/testutils/__init__.py2
-rw-r--r--pylint/testutils/checker_test_case.py2
-rw-r--r--pylint/testutils/configuration_test.py2
-rw-r--r--pylint/testutils/get_test_info.py2
-rw-r--r--pylint/testutils/lint_module_test.py2
-rw-r--r--pylint/testutils/output_line.py4
-rw-r--r--pylint/testutils/primer.py20
-rw-r--r--pylint/testutils/reporter_for_tests.py8
-rw-r--r--pylint/typing.py10
-rw-r--r--pylint/utils/__init__.py2
-rw-r--r--pylint/utils/ast_walker.py2
-rw-r--r--pylint/utils/docs.py8
-rw-r--r--pylint/utils/file_state.py4
-rw-r--r--pylint/utils/linterstats.py46
-rw-r--r--pylint/utils/pragma_parser.py6
-rw-r--r--pylint/utils/utils.py20
-rw-r--r--script/fix_documentation.py2
-rw-r--r--script/get_unused_message_id_category.py4
-rw-r--r--tests/benchmark/test_baseline_benchmarks.py36
-rw-r--r--tests/checkers/unittest_design.py2
-rw-r--r--tests/checkers/unittest_format.py6
-rw-r--r--tests/checkers/unittest_non_ascii_name.py6
-rw-r--r--tests/checkers/unittest_similar.py2
-rw-r--r--tests/checkers/unittest_typecheck.py2
-rw-r--r--tests/checkers/unittest_unicode/unittest_bad_chars.py4
-rw-r--r--tests/checkers/unittest_unicode/unittest_bidirectional_unicode.py2
-rw-r--r--tests/checkers/unittest_unicode/unittest_functions.py4
-rw-r--r--tests/checkers/unittest_unicode/unittest_invalid_encoding.py4
-rw-r--r--tests/checkers/unittest_utils.py2
-rw-r--r--tests/config/file_to_lint.py2
-rw-r--r--tests/config/unittest_config.py2
-rw-r--r--tests/conftest.py2
-rw-r--r--tests/extensions/test_check_docs_utils.py2
-rw-r--r--tests/lint/unittest_expand_modules.py8
-rw-r--r--tests/lint/unittest_lint.py4
-rw-r--r--tests/message/unittest_message_id_store.py2
-rw-r--r--tests/primer/test_primer_external.py6
-rw-r--r--tests/primer/test_primer_stdlib.py2
-rw-r--r--tests/profile/test_profile_against_externals.py4
-rw-r--r--tests/pyreverse/conftest.py2
-rw-r--r--tests/pyreverse/test_diadefs.py14
-rw-r--r--tests/pyreverse/test_diagrams.py2
-rw-r--r--tests/pyreverse/test_inspector.py2
-rw-r--r--tests/pyreverse/test_main.py2
-rw-r--r--tests/pyreverse/test_printer_factory.py2
-rw-r--r--tests/pyreverse/test_utils.py6
-rw-r--r--tests/pyreverse/test_writer.py4
-rw-r--r--tests/test_check_parallel.py34
-rw-r--r--tests/test_epylint.py2
-rw-r--r--tests/test_func.py4
-rw-r--r--tests/test_import_graph.py4
-rw-r--r--tests/test_pylint_runners.py2
-rw-r--r--tests/test_regr.py2
-rw-r--r--tests/test_self.py6
-rw-r--r--tests/testutils/test_decorator.py2
-rw-r--r--tests/unittest_reporters_json.py4
-rw-r--r--tests/unittest_reporting.py6
-rw-r--r--tests/utils/unittest_utils.py2
144 files changed, 770 insertions, 770 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index d62513592..33de05026 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -96,7 +96,7 @@ repos:
args: [--prose-wrap=always, --print-width=88]
exclude: tests(/.*)*/data
- repo: https://github.com/DanielNoord/pydocstringformatter
- rev: v0.2.0
+ rev: v0.4.0
hooks:
- id: pydocstringformatter
exclude: *fixtures
diff --git a/doc/exts/pylint_extensions.py b/doc/exts/pylint_extensions.py
index 2d1e91948..d8f8dfeca 100755
--- a/doc/exts/pylint_extensions.py
+++ b/doc/exts/pylint_extensions.py
@@ -16,7 +16,7 @@ from pylint.utils import get_rst_title
def builder_inited(app):
- """Output full documentation in ReST format for all extension modules"""
+ """Output full documentation in ReST format for all extension modules."""
# PACKAGE/docs/exts/pylint_extensions.py --> PACKAGE/
base_path = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
diff --git a/doc/exts/pylint_messages.py b/doc/exts/pylint_messages.py
index 32541788f..1ca3bdb88 100644
--- a/doc/exts/pylint_messages.py
+++ b/doc/exts/pylint_messages.py
@@ -18,10 +18,10 @@ from pylint.message import MessageDefinition
from pylint.utils import get_rst_title
PYLINT_BASE_PATH = Path(__file__).resolve().parent.parent.parent
-"""Base path to the project folder"""
+"""Base path to the project folder."""
PYLINT_MESSAGES_PATH = PYLINT_BASE_PATH / "doc" / "messages"
-"""Path to the messages documentation folder"""
+"""Path to the messages documentation folder."""
MSG_TYPES_DOC = {k: v if v != "info" else "information" for k, v in MSG_TYPES.items()}
@@ -218,7 +218,7 @@ def build_messages_pages(app: Optional[Sphinx]) -> None:
def setup(app: Sphinx) -> None:
- """Connects the extension to the Sphinx process"""
+ """Connects the extension to the Sphinx process."""
# Register callback at the builder-inited Sphinx event
# See https://www.sphinx-doc.org/en/master/extdev/appapi.html
app.connect("builder-inited", build_messages_pages)
diff --git a/examples/custom_raw.py b/examples/custom_raw.py
index 045f22ff4..365e9b7fa 100644
--- a/examples/custom_raw.py
+++ b/examples/custom_raw.py
@@ -10,7 +10,7 @@ if TYPE_CHECKING:
class MyRawChecker(BaseChecker):
- """check for line continuations with '\' instead of using triple
+ """Check for line continuations with '\' instead of using triple
quoted string or parenthesis
"""
@@ -30,7 +30,7 @@ class MyRawChecker(BaseChecker):
options = ()
def process_module(self, node: nodes.Module) -> None:
- """process a module
+ """Process a module.
the module's content is accessible via node.stream() function
"""
diff --git a/pylint/__init__.py b/pylint/__init__.py
index 16d81d903..02df46054 100644
--- a/pylint/__init__.py
+++ b/pylint/__init__.py
@@ -19,7 +19,7 @@ from pylint.__pkginfo__ import __version__
def run_pylint(argv: Optional[Sequence[str]] = None):
- """Run pylint
+ """Run pylint.
argv can be a sequence of strings normally supplied as arguments on the command line
"""
@@ -32,7 +32,7 @@ def run_pylint(argv: Optional[Sequence[str]] = None):
def run_epylint(argv: Optional[Sequence[str]] = None):
- """Run epylint
+ """Run epylint.
argv can be a list of strings normally supplied as arguments on the command line
"""
@@ -42,7 +42,7 @@ def run_epylint(argv: Optional[Sequence[str]] = None):
def run_pyreverse(argv: Optional[Sequence[str]] = None):
- """Run pyreverse
+ """Run pyreverse.
argv can be a sequence of strings normally supplied as arguments on the command line
"""
@@ -52,7 +52,7 @@ def run_pyreverse(argv: Optional[Sequence[str]] = None):
def run_symilar(argv: Optional[Sequence[str]] = None):
- """Run symilar
+ """Run symilar.
argv can be a sequence of strings normally supplied as arguments on the command line
"""
diff --git a/pylint/__pkginfo__.py b/pylint/__pkginfo__.py
index b2546d3a1..9e0f1edaa 100644
--- a/pylint/__pkginfo__.py
+++ b/pylint/__pkginfo__.py
@@ -6,7 +6,7 @@ __version__ = "2.13.0-dev0"
def get_numversion_from_version(v: str) -> Tuple:
- """Kept for compatibility reason
+ """Kept for compatibility reason.
See https://github.com/PyCQA/pylint/issues/4399
https://github.com/PyCQA/pylint/issues/4420,
diff --git a/pylint/checkers/__init__.py b/pylint/checkers/__init__.py
index 5ca89f749..e99560faa 100644
--- a/pylint/checkers/__init__.py
+++ b/pylint/checkers/__init__.py
@@ -19,7 +19,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
-"""utilities methods and classes for checkers
+"""Utilities methods and classes for checkers.
Base id of standard checkers (used in msg and report ids):
01: base
@@ -75,7 +75,7 @@ def table_lines_from_stats(
old_stats: Optional[LinterStats],
stat_type: Literal["duplicated_lines", "message_types"],
) -> List[str]:
- """get values listed in <columns> from <stats> and <old_stats>,
+ """Get values listed in <columns> from <stats> and <old_stats>,
and return a formatted list of values, designed to be given to a
ureport.Table object
"""
@@ -138,7 +138,7 @@ def table_lines_from_stats(
def initialize(linter):
- """initialize linter with checkers in this package"""
+ """Initialize linter with checkers in this package."""
register_plugins(linter, __path__[0])
diff --git a/pylint/checkers/base.py b/pylint/checkers/base.py
index 8ed43810f..e2a3ece49 100644
--- a/pylint/checkers/base.py
+++ b/pylint/checkers/base.py
@@ -68,7 +68,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
-"""basic checker for Python code"""
+"""Basic checker for Python code."""
import collections
import itertools
import re
@@ -261,12 +261,12 @@ LOOPLIKE_NODES = (
def in_loop(node: nodes.NodeNG) -> bool:
- """Return whether the node is inside a kind of for loop"""
+ """Return whether the node is inside a kind of for loop."""
return any(isinstance(parent, LOOPLIKE_NODES) for parent in node.node_ancestors())
def in_nested_list(nested_list, obj):
- """return true if the object is an element of <nested_list> or of a nested
+ """Return true if the object is an element of <nested_list> or of a nested
list
"""
for elmt in nested_list:
@@ -401,7 +401,7 @@ def report_by_type_stats(
stats: LinterStats,
old_stats: Optional[LinterStats],
):
- """make a report of
+ """Make a report of.
* percentage of different types documented
* percentage of different types with a bad name
@@ -438,7 +438,7 @@ def report_by_type_stats(
def redefined_by_decorator(node):
- """return True if the object is a method redefined via decorator.
+ """Return True if the object is a method redefined via decorator.
For example:
@property
@@ -749,7 +749,7 @@ class BasicErrorChecker(_BasicChecker):
@utils.check_messages("nonexistent-operator")
def visit_unaryop(self, node: nodes.UnaryOp) -> None:
- """Check use of the non-existent ++ and -- operators"""
+ """Check use of the non-existent ++ and -- operators."""
if (
(node.op in "+-")
and isinstance(node.operand, nodes.UnaryOp)
@@ -844,7 +844,7 @@ class BasicErrorChecker(_BasicChecker):
)
def _check_in_loop(self, node, node_name):
- """check that a node is inside a for or while loop"""
+ """Check that a node is inside a for or while loop."""
for parent in node.node_ancestors():
if isinstance(parent, (nodes.For, nodes.While)):
if node not in parent.orelse:
@@ -862,7 +862,7 @@ class BasicErrorChecker(_BasicChecker):
self.add_message("not-in-loop", node=node, args=node_name)
def _check_redefinition(self, redeftype, node):
- """check for redefinition of a function / method / class name"""
+ """Check for redefinition of a function / method / class name."""
parent_frame = node.parent.frame(future=True)
# Ignore function stubs created for type information
@@ -939,7 +939,7 @@ class BasicErrorChecker(_BasicChecker):
class BasicChecker(_BasicChecker):
- """checks for :
+ """Checks for :
* doc strings
* number of arguments, local variables, branches, returns and statements in
functions, methods
@@ -1089,7 +1089,7 @@ class BasicChecker(_BasicChecker):
self._tryfinallys = None
def open(self):
- """initialize visit variables and statistics"""
+ """Initialize visit variables and statistics."""
py_version = get_global_option(self, "py-version")
self._py38_plus = py_version >= (3, 8)
self._tryfinallys = []
@@ -1163,11 +1163,11 @@ class BasicChecker(_BasicChecker):
self.add_message("using-constant-test", node=node)
def visit_module(self, _: nodes.Module) -> None:
- """check module name, docstring and required arguments"""
+ """Check module name, docstring and required arguments."""
self.linter.stats.node_count["module"] += 1
def visit_classdef(self, _: nodes.ClassDef) -> None:
- """check module name, docstring and redefinition
+ """Check module name, docstring and redefinition
increment branch counter
"""
self.linter.stats.node_count["klass"] += 1
@@ -1176,7 +1176,7 @@ class BasicChecker(_BasicChecker):
"pointless-statement", "pointless-string-statement", "expression-not-assigned"
)
def visit_expr(self, node: nodes.Expr) -> None:
- """Check for various kind of statements without effect"""
+ """Check for various kind of statements without effect."""
expr = node.value
if isinstance(expr, nodes.Const) and isinstance(expr.value, str):
# treat string statement in a separated message
@@ -1246,7 +1246,7 @@ class BasicChecker(_BasicChecker):
@utils.check_messages("unnecessary-lambda")
def visit_lambda(self, node: nodes.Lambda) -> None:
- """Check whether the lambda is suspicious"""
+ """Check whether the lambda is suspicious."""
# if the body of the lambda is a call expression with the same
# argument list as the lambda itself, then the lambda is
# possibly unnecessary and at least suspicious.
@@ -1306,7 +1306,7 @@ class BasicChecker(_BasicChecker):
@utils.check_messages("dangerous-default-value")
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
- """check function name, docstring, arguments, redefinition,
+ """Check function name, docstring, arguments, redefinition,
variable names, max locals
"""
if node.is_method():
@@ -1370,7 +1370,7 @@ class BasicChecker(_BasicChecker):
@utils.check_messages("unreachable")
def visit_continue(self, node: nodes.Continue) -> None:
- """check is the node has a right sibling (if so, that's some unreachable
+ """Check is the node has a right sibling (if so, that's some unreachable
code)
"""
self._check_unreachable(node)
@@ -1389,7 +1389,7 @@ class BasicChecker(_BasicChecker):
@utils.check_messages("unreachable")
def visit_raise(self, node: nodes.Raise) -> None:
- """check if the node has a right sibling (if so, that's some unreachable
+ """Check if the node has a right sibling (if so, that's some unreachable
code)
"""
self._check_unreachable(node)
@@ -1419,7 +1419,7 @@ class BasicChecker(_BasicChecker):
"eval-used", "exec-used", "bad-reversed-sequence", "misplaced-format-function"
)
def visit_call(self, node: nodes.Call) -> None:
- """visit a Call node -> check if this is not a disallowed builtin
+ """Visit a Call node -> check if this is not a disallowed builtin
call and check for * or ** use
"""
self._check_misplaced_format_function(node)
@@ -1437,7 +1437,7 @@ class BasicChecker(_BasicChecker):
@utils.check_messages("assert-on-tuple", "assert-on-string-literal")
def visit_assert(self, node: nodes.Assert) -> None:
- """check whether assert is used on a tuple or string literal."""
+ """Check whether assert is used on a tuple or string literal."""
if (
node.fail is None
and isinstance(node.test, nodes.Tuple)
@@ -1454,7 +1454,7 @@ class BasicChecker(_BasicChecker):
@utils.check_messages("duplicate-key")
def visit_dict(self, node: nodes.Dict) -> None:
- """check duplicate key in dictionary"""
+ """Check duplicate key in dictionary."""
keys = set()
for k, _ in node.items:
if isinstance(k, nodes.Const):
@@ -1468,15 +1468,15 @@ class BasicChecker(_BasicChecker):
keys.add(key)
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
- """update try...finally flag"""
+ """Update try...finally flag."""
self._tryfinallys.append(node)
def leave_tryfinally(self, _: nodes.TryFinally) -> None:
- """update try...finally flag"""
+ """Update try...finally flag."""
self._tryfinallys.pop()
def _check_unreachable(self, node):
- """check unreachable code"""
+ """Check unreachable code."""
unreach_stmt = node.next_sibling()
if unreach_stmt is not None:
if (
@@ -1492,7 +1492,7 @@ class BasicChecker(_BasicChecker):
self.add_message("unreachable", node=unreach_stmt)
def _check_not_in_finally(self, node, node_name, breaker_classes=()):
- """check that a node is not inside a 'finally' clause of a
+ """Check that a node is not inside a 'finally' clause of a
'try...finally' statement.
If we find a parent which type is in breaker_classes before
a 'try...finally' block we skip the whole check.
@@ -1511,7 +1511,7 @@ class BasicChecker(_BasicChecker):
_parent = _node.parent
def _check_reversed(self, node):
- """check that the argument to `reversed` is a sequence"""
+ """Check that the argument to `reversed` is a sequence."""
try:
argument = utils.safe_infer(utils.get_argument_from_call(node, position=0))
except utils.NoSuchArgumentError:
@@ -1942,7 +1942,7 @@ class NameChecker(_BasicChecker):
@utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword")
def visit_assignname(self, node: nodes.AssignName) -> None:
- """check module level assigned names"""
+ """Check module level assigned names."""
self._check_assign_to_new_keyword_violation(node.name, node)
frame = node.frame(future=True)
assign_type = node.assign_type()
@@ -1981,7 +1981,7 @@ class NameChecker(_BasicChecker):
self._check_name("class_attribute", node.name, node)
def _recursive_check_names(self, args):
- """check names in a possibly recursive list <arg>"""
+ """Check names in a possibly recursive list <arg>."""
for arg in args:
if isinstance(arg, nodes.AssignName):
self._check_name("argument", arg.name, arg)
@@ -2029,7 +2029,7 @@ class NameChecker(_BasicChecker):
)
def _check_name(self, node_type, name, node, confidence=interfaces.HIGH):
- """check for a name using the type's regexp"""
+ """Check for a name using the type's regexp."""
def _should_exempt_from_invalid_name(node):
if node_type == "variable":
@@ -2190,7 +2190,7 @@ class DocStringChecker(_BasicChecker):
report_missing=True,
confidence=interfaces.HIGH,
):
- """Check if the node has a non-empty docstring"""
+ """Check if the node has a non-empty docstring."""
docstring = node.doc
if docstring is None:
docstring = _infer_dunder_doc_attribute(node)
@@ -2243,7 +2243,7 @@ class DocStringChecker(_BasicChecker):
class PassChecker(_BasicChecker):
- """check if the pass statement is really necessary"""
+ """Check if the pass statement is really necessary."""
msgs = {
"W0107": (
@@ -2285,7 +2285,7 @@ def _infer_dunder_doc_attribute(node):
class ComparisonChecker(_BasicChecker):
- """Checks for comparisons
+ """Checks for comparisons.
- singleton comparison: 'expr == True', 'expr == False' and 'expr == None'
- yoda condition: 'const "comp" right' where comp can be '==', '!=', '<',
@@ -2339,7 +2339,7 @@ class ComparisonChecker(_BasicChecker):
def _check_singleton_comparison(
self, left_value, right_value, root_node, checking_for_absence: bool = False
):
- """Check if == or != is being used to compare a singleton value"""
+ """Check if == or != is being used to compare a singleton value."""
singleton_values = (True, False, None)
def _is_singleton_const(node) -> bool:
diff --git a/pylint/checkers/base_checker.py b/pylint/checkers/base_checker.py
index 5a6efd20c..10e990f93 100644
--- a/pylint/checkers/base_checker.py
+++ b/pylint/checkers/base_checker.py
@@ -48,7 +48,7 @@ class BaseChecker(OptionsProviderMixIn):
enabled: bool = True
def __init__(self, linter=None):
- """checker instances should have the linter as argument
+ """Checker instances should have the linter as argument.
:param ILinter linter: is an object implementing ILinter.
"""
@@ -189,10 +189,10 @@ class BaseChecker(OptionsProviderMixIn):
raise InvalidMessageError(error_msg)
def open(self):
- """called before visiting project (i.e. set of modules)"""
+ """Called before visiting project (i.e. set of modules)."""
def close(self):
- """called after visiting project (i.e set of modules)"""
+ """Called after visiting project (i.e set of modules)."""
class BaseTokenChecker(BaseChecker):
diff --git a/pylint/checkers/classes/class_checker.py b/pylint/checkers/classes/class_checker.py
index 513b27308..dcde9231b 100644
--- a/pylint/checkers/classes/class_checker.py
+++ b/pylint/checkers/classes/class_checker.py
@@ -49,7 +49,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
-"""Classes checker for Python code"""
+"""Classes checker for Python code."""
import collections
from itertools import chain, zip_longest
from typing import Dict, List, Pattern, Set
@@ -186,7 +186,7 @@ _DEFAULT_MISSING = _DefaultMissing()
def _has_different_parameters_default_value(original, overridden):
- """Check if original and overridden methods arguments have different default values
+ """Check if original and overridden methods arguments have different default values.
Return True if one of the overridden arguments has a default
value different from the default value of the original argument
@@ -257,7 +257,7 @@ def _different_parameters(
overridden: nodes.FunctionDef,
dummy_parameter_regex: Pattern,
) -> List[str]:
- """Determine if the two methods have different parameters
+ """Determine if the two methods have different parameters.
They are considered to have different parameters if:
@@ -690,7 +690,7 @@ class ScopeAccessMap:
class ClassChecker(BaseChecker):
- """checks for :
+ """Checks for :
* methods without self as first argument
* overridden methods signature
* access only to existent members via self
@@ -800,7 +800,7 @@ a metaclass class method.",
"redefined-slots-in-subclass",
)
def visit_classdef(self, node: nodes.ClassDef) -> None:
- """init visit variable _accessed"""
+ """Init visit variable _accessed."""
self._check_bases_classes(node)
# if not an exception or a metaclass
if node.type == "class" and has_known_bases(node):
@@ -849,7 +849,7 @@ a metaclass class method.",
)
def _check_typing_final(self, node: nodes.ClassDef) -> None:
- """Detect that a class does not subclass a class decorated with `typing.final`"""
+ """Detect that a class does not subclass a class decorated with `typing.final`."""
if not self._py38_plus:
return
for base in node.bases:
@@ -869,7 +869,7 @@ a metaclass class method.",
@check_messages("unused-private-member", "attribute-defined-outside-init")
def leave_classdef(self, node: nodes.ClassDef) -> None:
- """close a class node:
+ """Close a class node:
check that instance attributes are defined in __init__ and check
access to existent members
"""
@@ -929,7 +929,7 @@ a metaclass class method.",
)
def _check_unused_private_variables(self, node: nodes.ClassDef) -> None:
- """Check if private variables are never used within a class"""
+ """Check if private variables are never used within a class."""
for assign_name in node.nodes_of_class(nodes.AssignName):
if isinstance(assign_name.parent, nodes.Arguments):
continue # Ignore function arguments
@@ -1074,7 +1074,7 @@ a metaclass class method.",
)
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
- """check method arguments, overriding"""
+ """Check method arguments, overriding."""
# ignore actual functions
if not node.is_method():
return
@@ -1171,7 +1171,7 @@ a metaclass class method.",
visit_asyncfunctiondef = visit_functiondef
def _check_useless_super_delegation(self, function):
- """Check if the given function node is an useless method override
+ """Check if the given function node is an useless method override.
We consider it *useless* if it uses the super() builtin, but having
nothing additional whatsoever than not implementing the method at all.
@@ -1370,7 +1370,7 @@ a metaclass class method.",
slots_node: nodes.NodeNG,
slots_list: List[nodes.NodeNG],
) -> None:
- """Check if `node` redefines a slot which is defined in an ancestor class"""
+ """Check if `node` redefines a slot which is defined in an ancestor class."""
slots_names: List[str] = []
for slot in slots_list:
if isinstance(slot, nodes.Const):
@@ -1426,7 +1426,7 @@ a metaclass class method.",
)
def leave_functiondef(self, node: nodes.FunctionDef) -> None:
- """on method node, check if this method couldn't be a function
+ """On method node, check if this method couldn't be a function.
ignore class, static and abstract methods, initializer,
methods overridden from a parent class.
@@ -1455,7 +1455,7 @@ a metaclass class method.",
leave_asyncfunctiondef = leave_functiondef
def visit_attribute(self, node: nodes.Attribute) -> None:
- """check if the getattr is an access to a class member
+ """Check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods)
@@ -1566,7 +1566,7 @@ a metaclass class method.",
self._check_protected_attribute_access(node)
def _check_classmethod_declaration(self, node):
- """Checks for uses of classmethod() or staticmethod()
+ """Checks for uses of classmethod() or staticmethod().
When a @classmethod or @staticmethod decorator should be used instead.
A message will be emitted only if the assignment is at a class scope
@@ -1699,7 +1699,7 @@ a metaclass class method.",
@staticmethod
def _is_called_inside_special_method(node: nodes.NodeNG) -> bool:
- """Returns true if the node is located inside a special (aka dunder) method"""
+ """Returns true if the node is located inside a special (aka dunder) method."""
frame_name = node.frame(future=True).name
return frame_name and frame_name in PYMETHODS
@@ -1751,7 +1751,7 @@ a metaclass class method.",
return False
def visit_name(self, node: nodes.Name) -> None:
- """check if the name handle an access to a class member
+ """Check if the name handle an access to a class member
if so, register it
"""
if self._first_attrs and (
@@ -1760,7 +1760,7 @@ a metaclass class method.",
self._meth_could_be_func = False
def _check_accessed_members(self, node, accessed):
- """check that accessed members are defined"""
+ """Check that accessed members are defined."""
excs = ("AttributeError", "Exception", "BaseException")
for attr, nodes_lst in accessed.items():
try:
@@ -1820,7 +1820,7 @@ a metaclass class method.",
)
def _check_first_arg_for_type(self, node, metaclass=0):
- """check the name of first argument, expect:
+ """Check the name of first argument, expect:.
* 'self' for a regular method
* 'cls' for a class method or a metaclass regular method (actually
@@ -1896,7 +1896,7 @@ a metaclass class method.",
self.add_message(message, args=(method_name, valid), node=node)
def _check_bases_classes(self, node):
- """check that the given class node implements abstract methods from
+ """Check that the given class node implements abstract methods from
base classes
"""
@@ -1923,7 +1923,7 @@ a metaclass class method.",
self.add_message("abstract-method", node=node, args=(name, owner.name))
def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None:
- """check that the __init__ method call super or ancestors'__init__
+ """Check that the __init__ method call super or ancestors'__init__
method (unless it is used for type hinting with `typing.overload`)
"""
if not self.linter.is_message_enabled(
@@ -2006,7 +2006,7 @@ a metaclass class method.",
)
def _check_signature(self, method1, refmethod, class_type, cls):
- """check that the signature of the two given methods match"""
+ """Check that the signature of the two given methods match."""
if not (
isinstance(method1, nodes.FunctionDef)
and isinstance(refmethod, nodes.FunctionDef)
@@ -2084,14 +2084,14 @@ a metaclass class method.",
)
def _uses_mandatory_method_param(self, node):
- """Check that attribute lookup name use first attribute variable name
+ """Check that attribute lookup name use first attribute variable name.
Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
"""
return self._is_mandatory_method_param(node.expr)
def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool:
- """Check if nodes.Name corresponds to first attribute variable name
+ """Check if nodes.Name corresponds to first attribute variable name.
Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
"""
@@ -2113,7 +2113,7 @@ a metaclass class method.",
def _ancestors_to_call(
klass_node: nodes.ClassDef, method="__init__"
) -> Dict[nodes.ClassDef, bases.UnboundMethod]:
- """return a dictionary where keys are the list of base classes providing
+ """Return a dictionary where keys are the list of base classes providing
the queried method, and so that should/may be called from the method node
"""
to_call: Dict[nodes.ClassDef, bases.UnboundMethod] = {}
diff --git a/pylint/checkers/classes/special_methods_checker.py b/pylint/checkers/classes/special_methods_checker.py
index f26823007..7eb61440d 100644
--- a/pylint/checkers/classes/special_methods_checker.py
+++ b/pylint/checkers/classes/special_methods_checker.py
@@ -1,7 +1,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
-"""Special methods checker and helper function's module"""
+"""Special methods checker and helper function's module."""
import astroid
from astroid import nodes
diff --git a/pylint/checkers/deprecated.py b/pylint/checkers/deprecated.py
index ac1cd6425..dc0713a89 100644
--- a/pylint/checkers/deprecated.py
+++ b/pylint/checkers/deprecated.py
@@ -70,7 +70,7 @@ class DeprecatedMixin(BaseChecker):
"deprecated-class",
)
def visit_import(self, node: nodes.Import) -> None:
- """triggered when an import statement is seen"""
+ """Triggered when an import statement is seen."""
for name in (name for name, _ in node.names):
self.check_deprecated_module(node, name)
if "." in name:
@@ -89,7 +89,7 @@ class DeprecatedMixin(BaseChecker):
@utils.check_messages("deprecated-decorator")
def visit_decorators(self, node: nodes.Decorators) -> None:
- """Triggered when a decorator statement is seen"""
+ """Triggered when a decorator statement is seen."""
children = list(node.get_children())
if not children:
return
@@ -106,7 +106,7 @@ class DeprecatedMixin(BaseChecker):
"deprecated-class",
)
def visit_importfrom(self, node: nodes.ImportFrom) -> None:
- """triggered when a from statement is seen"""
+ """Triggered when a from statement is seen."""
basename = node.modname
basename = get_import_name(node, basename)
self.check_deprecated_module(node, basename)
@@ -174,7 +174,7 @@ class DeprecatedMixin(BaseChecker):
return ()
def check_deprecated_module(self, node, mod_path):
- """Checks if the module is deprecated"""
+ """Checks if the module is deprecated."""
for mod_name in self.deprecated_modules():
if mod_path == mod_name or mod_path.startswith(mod_name + "."):
self.add_message("deprecated-module", node=node, args=mod_path)
@@ -225,7 +225,7 @@ class DeprecatedMixin(BaseChecker):
)
def check_deprecated_class(self, node, mod_name, class_names):
- """Checks if the class is deprecated"""
+ """Checks if the class is deprecated."""
for class_name in class_names:
if class_name in self.deprecated_classes(mod_name):
@@ -234,7 +234,7 @@ class DeprecatedMixin(BaseChecker):
)
def check_deprecated_class_in_call(self, node):
- """Checks if call the deprecated class"""
+ """Checks if call the deprecated class."""
if isinstance(node.func, nodes.Attribute) and isinstance(
node.func.expr, nodes.Name
diff --git a/pylint/checkers/design_analysis.py b/pylint/checkers/design_analysis.py
index ec518e857..94569d4ea 100644
--- a/pylint/checkers/design_analysis.py
+++ b/pylint/checkers/design_analysis.py
@@ -28,7 +28,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
-"""check for signs of poor design"""
+"""Check for signs of poor design."""
import re
from collections import defaultdict
@@ -193,7 +193,7 @@ STDLIB_CLASSES_IGNORE_ANCESTOR = frozenset(
def _is_exempt_from_public_methods(node: astroid.ClassDef) -> bool:
- """Check if a class is exempt from too-few-public-methods"""
+ """Check if a class is exempt from too-few-public-methods."""
# If it's a typing.Namedtuple, typing.TypedDict or an Enum
for ancestor in node.ancestors():
@@ -225,7 +225,7 @@ def _is_exempt_from_public_methods(node: astroid.ClassDef) -> bool:
def _count_boolean_expressions(bool_op):
- """Counts the number of boolean expressions in BoolOp `bool_op` (recursive)
+ """Counts the number of boolean expressions in BoolOp `bool_op` (recursive).
example: a and (b or c or (d and e)) ==> 5 boolean expressions
"""
@@ -291,7 +291,7 @@ def _get_parents(
class MisdesignChecker(BaseChecker):
- """checks for sign of poor/misdesign:
+ """Checks for sign of poor/misdesign:
* number of methods, attributes, local variables...
* size, complexity of functions, methods
"""
@@ -428,7 +428,7 @@ class MisdesignChecker(BaseChecker):
self._stmts = None
def open(self):
- """initialize visit variables"""
+ """Initialize visit variables."""
self.linter.stats.reset_node_count()
self._returns = []
self._branches = defaultdict(int)
@@ -452,7 +452,7 @@ class MisdesignChecker(BaseChecker):
"too-many-public-methods",
)
def visit_classdef(self, node: nodes.ClassDef) -> None:
- """check size of inheritance hierarchy and number of instance attributes"""
+ """Check size of inheritance hierarchy and number of instance attributes."""
parents = _get_parents(
node, STDLIB_CLASSES_IGNORE_ANCESTOR.union(self.config.ignored_parents)
)
@@ -473,7 +473,7 @@ class MisdesignChecker(BaseChecker):
@check_messages("too-few-public-methods", "too-many-public-methods")
def leave_classdef(self, node: nodes.ClassDef) -> None:
- """check number of public methods"""
+ """Check number of public methods."""
my_methods = sum(
1 for method in node.mymethods() if not method.name.startswith("_")
)
@@ -526,7 +526,7 @@ class MisdesignChecker(BaseChecker):
"keyword-arg-before-vararg",
)
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
- """check function name, docstring, arguments, redefinition,
+ """Check function name, docstring, arguments, redefinition,
variable names, max locals
"""
# init branch and returns counters
@@ -569,7 +569,7 @@ class MisdesignChecker(BaseChecker):
"too-many-statements",
)
def leave_functiondef(self, node: nodes.FunctionDef) -> None:
- """most of the work is done here on close:
+ """Most of the work is done here on close:
checks for max returns, branch, return in __init__
"""
returns = self._returns.pop()
@@ -598,20 +598,20 @@ class MisdesignChecker(BaseChecker):
leave_asyncfunctiondef = leave_functiondef
def visit_return(self, _: nodes.Return) -> None:
- """count number of returns"""
+ """Count number of returns."""
if not self._returns:
return # return outside function, reported by the base checker
self._returns[-1] += 1
def visit_default(self, node: nodes.NodeNG) -> None:
- """default visit method -> increments the statements counter if
+ """Default visit method -> increments the statements counter if
necessary
"""
if node.is_statement:
self._inc_all_stmts(1)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
- """increments the branches counter"""
+ """Increments the branches counter."""
branches = len(node.handlers)
if node.orelse:
branches += 1
@@ -619,13 +619,13 @@ class MisdesignChecker(BaseChecker):
self._inc_all_stmts(branches)
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
- """increments the branches counter"""
+ """Increments the branches counter."""
self._inc_branch(node, 2)
self._inc_all_stmts(2)
@check_messages("too-many-boolean-expressions")
def visit_if(self, node: nodes.If) -> None:
- """increments the branches counter and checks boolean expressions"""
+ """Increments the branches counter and checks boolean expressions."""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
@@ -652,7 +652,7 @@ class MisdesignChecker(BaseChecker):
)
def visit_while(self, node: nodes.While) -> None:
- """increments the branches counter"""
+ """Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
@@ -661,7 +661,7 @@ class MisdesignChecker(BaseChecker):
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
- """increments the branches counter"""
+ """Increments the branches counter."""
self._branches[node.scope()] += branchesnum
diff --git a/pylint/checkers/ellipsis_checker.py b/pylint/checkers/ellipsis_checker.py
index af8715ed5..f29ebed04 100644
--- a/pylint/checkers/ellipsis_checker.py
+++ b/pylint/checkers/ellipsis_checker.py
@@ -1,4 +1,4 @@
-"""Ellipsis checker for Python code"""
+"""Ellipsis checker for Python code."""
from typing import TYPE_CHECKING
from astroid import nodes
diff --git a/pylint/checkers/exceptions.py b/pylint/checkers/exceptions.py
index eafbafa2b..9960b8d32 100644
--- a/pylint/checkers/exceptions.py
+++ b/pylint/checkers/exceptions.py
@@ -75,7 +75,7 @@ def _annotated_unpack_infer(stmt, context=None):
def _is_raising(body: List) -> bool:
- """Return whether the given statement node raises an exception"""
+ """Return whether the given statement node raises an exception."""
return any(isinstance(node, nodes.Raise) for node in body)
@@ -506,7 +506,7 @@ class ExceptionsChecker(checkers.BaseChecker):
"duplicate-except",
)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
- """check for empty except"""
+ """Check for empty except."""
self._check_try_except_raise(node)
exceptions_classes: List[Any] = []
nb_handlers = len(node.handlers)
diff --git a/pylint/checkers/format.py b/pylint/checkers/format.py
index 4f5f01e55..fe505a66d 100644
--- a/pylint/checkers/format.py
+++ b/pylint/checkers/format.py
@@ -237,7 +237,7 @@ class TokenWrapper:
class FormatChecker(BaseTokenChecker):
- """checks for :
+ """Checks for :
* unauthorized constructions
* strict indentation
* line length
@@ -348,7 +348,7 @@ class FormatChecker(BaseTokenChecker):
self._bracket_stack = [None]
def new_line(self, tokens, line_end, line_start):
- """a new line has been encountered, process it if necessary"""
+ """A new line has been encountered, process it if necessary."""
if _last_token_on_line_is(tokens, line_end, ";"):
self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end))
@@ -471,7 +471,7 @@ class FormatChecker(BaseTokenChecker):
return dispatch
def process_tokens(self, tokens):
- """process tokens and search for :
+ """Process tokens and search for :.
_ too long lines (i.e. longer than <max_chars>)
_ optionally bad construct (if given, bad_construct must be a compiled
@@ -590,7 +590,7 @@ class FormatChecker(BaseTokenChecker):
@check_messages("multiple-statements")
def visit_default(self, node: nodes.NodeNG) -> None:
- """check the node line number and check it if not yet done"""
+ """Check the node line number and check it if not yet done."""
if not node.is_statement:
return
if not node.root().pure_python:
@@ -681,7 +681,7 @@ class FormatChecker(BaseTokenChecker):
)
def check_line_length(self, line: str, i: int, checker_off: bool) -> None:
- """Check that the line length is less than the authorized value"""
+ """Check that the line length is less than the authorized value."""
max_chars = self.config.max_line_length
ignore_long_line = self.config.ignore_long_lines
line = line.rstrip()
@@ -693,7 +693,7 @@ class FormatChecker(BaseTokenChecker):
@staticmethod
def remove_pylint_option_from_lines(options_pattern_obj) -> str:
- """Remove the `# pylint ...` pattern from lines"""
+ """Remove the `# pylint ...` pattern from lines."""
lines = options_pattern_obj.string
purged_lines = (
lines[: options_pattern_obj.start(1)].rstrip()
@@ -703,7 +703,7 @@ class FormatChecker(BaseTokenChecker):
@staticmethod
def is_line_length_check_activated(pylint_pattern_match_object) -> bool:
- """Return true if the line length check is activated"""
+ """Return true if the line length check is activated."""
try:
for pragma in parse_pragma(pylint_pattern_match_object.group(2)):
if pragma.action == "disable" and "line-too-long" in pragma.messages:
@@ -715,7 +715,7 @@ class FormatChecker(BaseTokenChecker):
@staticmethod
def specific_splitlines(lines: str) -> List[str]:
- """Split lines according to universal newlines except those in a specific sets"""
+ """Split lines according to universal newlines except those in a specific sets."""
unsplit_ends = {
"\v",
"\x0b",
@@ -788,7 +788,7 @@ class FormatChecker(BaseTokenChecker):
self.check_line_length(line, lineno + offset, checker_off)
def check_indent_level(self, string, expected, line_num):
- """return the indent level of the string"""
+ """Return the indent level of the string."""
indent = self.config.indent_string
if indent == "\\t": # \t is not interpreted in the configuration file
indent = "\t"
diff --git a/pylint/checkers/imports.py b/pylint/checkers/imports.py
index 3f639eef0..bd368a2c5 100644
--- a/pylint/checkers/imports.py
+++ b/pylint/checkers/imports.py
@@ -45,7 +45,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
-"""imports checkers for Python code"""
+"""Imports checkers for Python code."""
import collections
import copy
@@ -77,7 +77,7 @@ if TYPE_CHECKING:
def _qualified_names(modname):
- """Split the names of the given module into subparts
+ """Split the names of the given module into subparts.
For example,
_qualified_names('pylint.checkers.ImportsChecker')
@@ -89,7 +89,7 @@ def _qualified_names(modname):
def _get_first_import(node, context, name, base, level, alias):
- """return the node where [base.]<name> is imported or None if not found"""
+ """Return the node where [base.]<name> is imported or None if not found."""
fullname = f"{base}.{name}" if base else name
first = None
@@ -140,7 +140,7 @@ def _ignore_import_failure(node, modname, ignored_modules):
def _make_tree_defs(mod_files_list):
- """get a list of 2-uple (module, list_of_files_which_import_this_module),
+ """Get a list of 2-uple (module, list_of_files_which_import_this_module),
it will return a dictionary to represent this as a tree
"""
tree_defs = {}
@@ -153,7 +153,7 @@ def _make_tree_defs(mod_files_list):
def _repr_tree_defs(data, indent_str=None):
- """return a string which represents imports as a tree"""
+ """Return a string which represents imports as a tree."""
lines = []
nodes_items = data.items()
for i, (mod, (sub, files)) in enumerate(sorted(nodes_items, key=lambda x: x[0])):
@@ -173,7 +173,7 @@ def _repr_tree_defs(data, indent_str=None):
def _dependencies_graph(filename: str, dep_info: Dict[str, Set[str]]) -> str:
- """write dependencies as a dot (graphviz) file"""
+ """Write dependencies as a dot (graphviz) file."""
done = {}
printer = DotBackend(os.path.splitext(os.path.basename(filename))[0], rankdir="LR")
printer.emit('URL="." node[shape="box"]')
@@ -194,7 +194,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
):
- """generate a dependencies graph and add some information about it in the
+ """Generate a dependencies graph and add some information about it in the
report's section
"""
outputfile = _dependencies_graph(filename, dep_info)
@@ -302,7 +302,7 @@ DEFAULT_PREFERRED_MODULES = ()
class ImportsChecker(DeprecatedMixin, BaseChecker):
- """checks for
+ """Checks for
* external modules dependencies
* relative / wildcard imports
* cyclic imports
@@ -469,7 +469,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
return paths
def open(self):
- """called before visiting project (i.e set of modules)"""
+ """Called before visiting project (i.e set of modules)."""
self.linter.stats.dependencies = {}
self.linter.stats = self.linter.stats
self.import_graph = collections.defaultdict(set)
@@ -491,7 +491,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
return filtered_graph
def close(self):
- """called before visiting project (i.e set of modules)"""
+ """Called before visiting project (i.e set of modules)."""
if self.linter.is_message_enabled("cyclic-import"):
graph = self._import_graph_without_ignored_edges()
vertices = list(graph)
@@ -504,7 +504,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
@check_messages(*MSGS)
def visit_import(self, node: nodes.Import) -> None:
- """triggered when an import statement is seen"""
+ """Triggered when an import statement is seen."""
self._check_reimport(node)
self._check_import_as_rename(node)
self._check_toplevel(node)
@@ -530,7 +530,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
@check_messages(*MSGS)
def visit_importfrom(self, node: nodes.ImportFrom) -> None:
- """triggered when a from statement is seen"""
+ """Triggered when a from statement is seen."""
basename = node.modname
imported_module = self._get_imported_module(node, basename)
@@ -673,7 +673,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
self.add_message("reimported", node=node, args=(name, node.fromlineno))
def _check_position(self, node):
- """Check `node` import or importfrom node position is correct
+ """Check `node` import or importfrom node position is correct.
Send a message if `node` comes before another instruction
"""
@@ -683,7 +683,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
self.add_message("wrong-import-position", node=node, args=node.as_string())
def _record_import(self, node, importedmodnode):
- """Record the package `node` imports from"""
+ """Record the package `node` imports from."""
if isinstance(node, nodes.ImportFrom):
importedname = node.modname
else:
@@ -709,7 +709,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
return any(astroid.are_exclusive(import_node, node) for import_node in imports)
def _check_imports_order(self, _module_node):
- """Checks imports of module `node` are grouped by category
+ """Checks imports of module `node` are grouped by category.
Imports must follow this order: standard, 3rd party, local
"""
@@ -831,7 +831,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
def _add_imported_module(
self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str
) -> None:
- """notify an imported module, used to analyze dependencies"""
+ """Notify an imported module, used to analyze dependencies."""
module_file = node.root().file
context_name = node.root().name
base = os.path.splitext(os.path.basename(module_file))[0]
@@ -872,7 +872,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
self._excluded_edges[context_name].add(importedmodname)
def _check_preferred_module(self, node, mod_path):
- """check if the module has a preferred replacement"""
+ """Check if the module has a preferred replacement."""
if mod_path in self.preferred_modules:
self.add_message(
"preferred-module",
@@ -904,7 +904,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
)
def _check_reimport(self, node, basename=None, level=None):
- """check if the import is necessary (i.e. not already done)"""
+ """Check if the import is necessary (i.e. not already done)."""
if not self.linter.is_message_enabled("reimported"):
return
@@ -925,7 +925,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
)
def _report_external_dependencies(self, sect, _, _dummy):
- """return a verbatim layout for displaying dependencies"""
+ """Return a verbatim layout for displaying dependencies."""
dep_info = _make_tree_defs(self._external_dependencies_info().items())
if not dep_info:
raise EmptyReportError()
@@ -933,7 +933,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
sect.append(VerbatimText(tree_str))
def _report_dependencies_graph(self, sect, _, _dummy):
- """write dependencies as a dot (graphviz) file"""
+ """Write dependencies as a dot (graphviz) file."""
dep_info = self.linter.stats.dependencies
if not dep_info or not (
self.config.import_graph
@@ -952,7 +952,7 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
_make_graph(filename, self._internal_dependencies_info(), sect, "internal ")
def _filter_dependencies_graph(self, internal):
- """build the internal or the external dependency graph"""
+ """Build the internal or the external dependency graph."""
graph = collections.defaultdict(set)
for importee, importers in self.linter.stats.dependencies.items():
for importer in importers:
@@ -964,14 +964,14 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
@astroid.decorators.cached
def _external_dependencies_info(self):
- """return cached external dependencies information or build and
+ """Return cached external dependencies information or build and
cache them
"""
return self._filter_dependencies_graph(internal=False)
@astroid.decorators.cached
def _internal_dependencies_info(self):
- """return cached internal dependencies information or build and
+ """Return cached internal dependencies information or build and
cache them
"""
return self._filter_dependencies_graph(internal=True)
diff --git a/pylint/checkers/logging.py b/pylint/checkers/logging.py
index 4c4401741..aedaf6241 100644
--- a/pylint/checkers/logging.py
+++ b/pylint/checkers/logging.py
@@ -23,7 +23,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
-"""checker for use of Python logging"""
+"""Checker for use of Python logging."""
import string
from typing import TYPE_CHECKING, Set
@@ -294,7 +294,7 @@ class LoggingChecker(checkers.BaseChecker):
@staticmethod
def _is_operand_literal_str(operand):
- """Return True if the operand in argument is a literal string"""
+ """Return True if the operand in argument is a literal string."""
return isinstance(operand, nodes.Const) and operand.name == "str"
def _check_call_func(self, node: nodes.Call):
diff --git a/pylint/checkers/mapreduce_checker.py b/pylint/checkers/mapreduce_checker.py
index b1722fc9b..a4a2c605c 100644
--- a/pylint/checkers/mapreduce_checker.py
+++ b/pylint/checkers/mapreduce_checker.py
@@ -8,12 +8,12 @@ import abc
class MapReduceMixin(metaclass=abc.ABCMeta):
- """A mixin design to allow multiprocess/threaded runs of a Checker"""
+ """A mixin design to allow multiprocess/threaded runs of a Checker."""
@abc.abstractmethod
def get_map_data(self):
- """Returns mergeable/reducible data that will be examined"""
+ """Returns mergeable/reducible data that will be examined."""
@abc.abstractmethod
def reduce_map_data(self, linter, data):
- """For a given Checker, receives data for all mapped runs"""
+ """For a given Checker, receives data for all mapped runs."""
diff --git a/pylint/checkers/misc.py b/pylint/checkers/misc.py
index 5c3a9ab64..69149e61a 100644
--- a/pylint/checkers/misc.py
+++ b/pylint/checkers/misc.py
@@ -25,7 +25,7 @@
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
-"""Check source code is ascii only or has an encoding declaration (PEP 263)"""
+"""Check source code is ascii only or has an encoding declaration (PEP 263)."""
import re
import tokenize
@@ -76,7 +76,7 @@ class ByIdManagedMessagesChecker(BaseChecker):
class EncodingChecker(BaseChecker):
- """checks for:
+ """Checks for:
* warning notes in the code like FIXME, XXX
* encoding issues.
"""
@@ -145,7 +145,7 @@ class EncodingChecker(BaseChecker):
return None
def process_module(self, node: nodes.Module) -> None:
- """inspect the source file to find encoding problem"""
+ """Inspect the source file to find encoding problem."""
encoding = node.file_encoding if node.file_encoding else "ascii"
with node.stream() as stream:
@@ -153,7 +153,7 @@ class EncodingChecker(BaseChecker):
self._check_encoding(lineno + 1, line, encoding)
def process_tokens(self, tokens):
- """inspect the source to find fixme problems"""
+ """Inspect the source to find fixme problems."""
if not self.config.notes:
return
comments = (
diff --git a/pylint/checkers/newstyle.py b/pylint/checkers/newstyle.py
index 143550909..00fa0748e 100644
--- a/pylint/checkers/newstyle.py
+++ b/pylint/checkers/newstyle.py
@@ -20,7 +20,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
-"""check for new / old style related problems"""
+"""Check for new / old style related problems."""
from typing import TYPE_CHECKING
import astroid
@@ -44,7 +44,7 @@ MSGS = {
class NewStyleConflictChecker(BaseChecker):
- """checks for usage of new style capabilities on old style classes and
+ """Checks for usage of new style capabilities on old style classes and
other new/old styles conflicts problems
* use of property, __slots__, super
* "super" usage
@@ -62,7 +62,7 @@ class NewStyleConflictChecker(BaseChecker):
@check_messages("bad-super-call")
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
- """check use of super"""
+ """Check use of super."""
# ignore actual functions or method within a new style class
if not node.is_method():
return
diff --git a/pylint/checkers/non_ascii_names.py b/pylint/checkers/non_ascii_names.py
index 1ff2b67e8..d9b3bfd50 100644
--- a/pylint/checkers/non_ascii_names.py
+++ b/pylint/checkers/non_ascii_names.py
@@ -41,7 +41,7 @@ NON_ASCII_HELP = (
class NonAsciiNameChecker(base_checker.BaseChecker):
- """A strict name checker only allowing ASCII
+ """A strict name checker only allowing ASCII.
Note: This check only checks Names, so it ignores the content of
docstrings and comments!
@@ -147,7 +147,7 @@ class NonAsciiNameChecker(base_checker.BaseChecker):
@utils.check_messages("non-ascii-name")
def visit_assignname(self, node: nodes.AssignName) -> None:
- """check module level assigned names"""
+ """Check module level assigned names."""
# The NameChecker from which this Checker originates knows a lot of different
# versions of variables, i.e. constants, inline variables etc.
# To simplify we use only `variable` here, as we don't need to apply different
diff --git a/pylint/checkers/raw_metrics.py b/pylint/checkers/raw_metrics.py
index 379665eac..84e6c23c4 100644
--- a/pylint/checkers/raw_metrics.py
+++ b/pylint/checkers/raw_metrics.py
@@ -39,7 +39,7 @@ def report_raw_stats(
stats: LinterStats,
old_stats: Optional[LinterStats],
) -> None:
- """calculate percentage of code / doc / comment / empty"""
+ """Calculate percentage of code / doc / comment / empty."""
total_lines = stats.code_type_count["total"]
sect.description = f"{total_lines} lines have been analyzed"
lines = ["type", "number", "%", "previous", "difference"]
@@ -60,7 +60,7 @@ def report_raw_stats(
class RawMetricsChecker(BaseTokenChecker):
- """does not check anything but gives some raw metrics :
+ """Does not check anything but gives some raw metrics :
* total number of lines
* total number of code lines
* total number of docstring lines
@@ -83,11 +83,11 @@ class RawMetricsChecker(BaseTokenChecker):
super().__init__(linter)
def open(self):
- """init statistics"""
+ """Init statistics."""
self.linter.stats.reset_code_count()
def process_tokens(self, tokens):
- """update stats"""
+ """Update stats."""
i = 0
tokens = list(tokens)
while i < len(tokens):
@@ -100,7 +100,7 @@ JUNK = (tokenize.NL, tokenize.INDENT, tokenize.NEWLINE, tokenize.ENDMARKER)
def get_type(tokens, start_index):
- """return the line type : docstring, comment, code, empty"""
+ """Return the line type : docstring, comment, code, empty."""
i = start_index
start = tokens[i][2]
pos = start
diff --git a/pylint/checkers/refactoring/implicit_booleaness_checker.py b/pylint/checkers/refactoring/implicit_booleaness_checker.py
index c4b25eeb7..b1fa67278 100644
--- a/pylint/checkers/refactoring/implicit_booleaness_checker.py
+++ b/pylint/checkers/refactoring/implicit_booleaness_checker.py
@@ -145,7 +145,7 @@ class ImplicitBooleanessChecker(checkers.BaseChecker):
def _check_use_implicit_booleaness_not_comparison(
self, node: nodes.Compare
) -> None:
- """Check for left side and right side of the node for empty literals"""
+ """Check for left side and right side of the node for empty literals."""
is_left_empty_literal = utils.is_base_container(
node.left
) or utils.is_empty_dict_literal(node.left)
diff --git a/pylint/checkers/refactoring/not_checker.py b/pylint/checkers/refactoring/not_checker.py
index ec29dfb8e..d1710ea22 100644
--- a/pylint/checkers/refactoring/not_checker.py
+++ b/pylint/checkers/refactoring/not_checker.py
@@ -10,7 +10,7 @@ from pylint.checkers import utils
class NotChecker(checkers.BaseChecker):
- """checks for too many not in comparison expressions
+ """Checks for too many not in comparison expressions.
- "not not" should trigger a warning
- "not" followed by a comparison should trigger a warning
diff --git a/pylint/checkers/refactoring/refactoring_checker.py b/pylint/checkers/refactoring/refactoring_checker.py
index 25313494b..1bf75e77e 100644
--- a/pylint/checkers/refactoring/refactoring_checker.py
+++ b/pylint/checkers/refactoring/refactoring_checker.py
@@ -54,7 +54,7 @@ def _if_statement_is_always_returning(if_node, returning_node_class) -> bool:
def _is_trailing_comma(tokens: List[tokenize.TokenInfo], index: int) -> bool:
- """Check if the given token is a trailing comma
+ """Check if the given token is a trailing comma.
:param tokens: Sequence of modules tokens
:type tokens: list[tokenize.TokenInfo]
@@ -81,7 +81,7 @@ def _is_trailing_comma(tokens: List[tokenize.TokenInfo], index: int) -> bool:
return False
def get_curline_index_start():
- """Get the index denoting the start of the current line"""
+ """Get the index denoting the start of the current line."""
for subindex, token in enumerate(reversed(tokens[:index])):
# See Lib/tokenize.py and Lib/token.py in cpython for more info
if token.type == tokenize.NEWLINE:
@@ -173,13 +173,13 @@ class ConsiderUsingWithStack(NamedTuple):
return self.module_scope
def clear_all(self) -> None:
- """Convenience method to clear all stacks"""
+ """Convenience method to clear all stacks."""
for stack in self:
stack.clear()
class RefactoringChecker(checkers.BaseTokenChecker):
- """Looks for code which can be refactored
+ """Looks for code which can be refactored.
This checker also mixes the astroid and the token approaches
in order to create knowledge about whether an "else if" node
@@ -486,7 +486,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
)
def _is_actual_elif(self, node):
- """Check if the given node is an actual elif
+ """Check if the given node is an actual elif.
This is a problem we're having with the builtin ast module,
which splits `elif` branches into a separate if statement.
@@ -910,7 +910,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
self._check_stop_iteration_inside_generator(node)
def _check_stop_iteration_inside_generator(self, node):
- """Check if an exception of type StopIteration is raised inside a generator"""
+ """Check if an exception of type StopIteration is raised inside a generator."""
frame = node.frame(future=True)
if not isinstance(frame, nodes.FunctionDef) or not frame.is_generator():
return
@@ -926,7 +926,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
@staticmethod
def _check_exception_inherit_from_stopiteration(exc):
- """Return True if the exception node in argument inherit from StopIteration"""
+ """Return True if the exception node in argument inherit from StopIteration."""
stopiteration_qname = f"{utils.EXCEPTIONS_MODULE}.StopIteration"
return any(_class.qname() == stopiteration_qname for _class in exc.mro())
@@ -1050,7 +1050,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
self.add_message("super-with-arguments", node=node)
def _check_raising_stopiteration_in_generator_next_call(self, node):
- """Check if a StopIteration exception is raised by the call to next function
+ """Check if a StopIteration exception is raised by the call to next function.
If the next value has a default value, then do not add message.
@@ -1084,7 +1084,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
self.add_message("stop-iteration-return", node=node)
def _check_nested_blocks(self, node):
- """Update and check the number of nested blocks"""
+ """Update and check the number of nested blocks."""
# only check block levels inside functions or methods
if not isinstance(node.scope(), nodes.FunctionDef):
return
@@ -1273,7 +1273,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
@staticmethod
def _apply_boolean_simplification_rules(operator, values):
- """Removes irrelevant values or returns shortcircuiting values
+ """Removes irrelevant values or returns shortcircuiting values.
This function applies the following two rules:
1) an OR expression with True in it will always be true, and the
@@ -1299,7 +1299,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
return simplified_values or [nodes.Const(operator == "and")]
def _simplify_boolean_operation(self, bool_op):
- """Attempts to simplify a boolean operation
+ """Attempts to simplify a boolean operation.
Recursively applies simplification on the operator terms,
and keeps track of whether reductions have been made.
@@ -1503,7 +1503,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
- """Check if empty list or dict is created by using the literal [] or {}"""
+ """Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
@@ -1798,7 +1798,7 @@ class RefactoringChecker(checkers.BaseTokenChecker):
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
- """Returns True if there is at least one return in the node's siblings"""
+ """Returns True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
diff --git a/pylint/checkers/similar.py b/pylint/checkers/similar.py
index ed85c34b3..113b086bc 100644
--- a/pylint/checkers/similar.py
+++ b/pylint/checkers/similar.py
@@ -27,7 +27,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
-"""a similarities / code duplication command line tool and pylint checker
+"""A similarities / code duplication command line tool and pylint checker.
The algorithm is based on comparing the hash value of n successive lines of a file.
First the files are read and any line that doesn't fulfill requirement are removed (comments, docstrings...)
@@ -139,13 +139,13 @@ class LinesChunk:
def __init__(self, fileid: str, num_line: int, *lines: Iterable[str]) -> None:
self._fileid: str = fileid
- """The name of the file from which the LinesChunk object is generated """
+ """The name of the file from which the LinesChunk object is generated."""
self._index: Index = Index(num_line)
- """The index in the stripped lines that is the starting of consecutive lines"""
+ """The index in the stripped lines that is the starting of consecutive lines."""
self._hash: int = sum(hash(lin) for lin in lines)
- """The hash of some consecutive lines"""
+ """The hash of some consecutive lines."""
def __eq__(self, o: Any) -> bool:
if not isinstance(o, LinesChunk):
@@ -196,7 +196,7 @@ class SuccessiveLinesLimits:
class LineSetStartCouple(NamedTuple):
- """Indices in both linesets that mark the beginning of successive lines"""
+ """Indices in both linesets that mark the beginning of successive lines."""
fst_lineset_index: Index
snd_lineset_index: Index
@@ -269,7 +269,7 @@ def hash_lineset(
def remove_successives(all_couples: CplIndexToCplLines_T) -> None:
- """Removes all successive entries in the dictionary in argument
+ """Removes all successive entries in the dictionary in argument.
:param all_couples: collection that has to be cleaned up from successives entries.
The keys are couples of indices that mark the beginning of common entries
@@ -353,7 +353,7 @@ class Commonality(NamedTuple):
class Similar:
- """finds copy-pasted lines of code in a project"""
+ """Finds copy-pasted lines of code in a project."""
def __init__(
self,
@@ -373,7 +373,7 @@ class Similar:
def append_stream(
self, streamid: str, stream: STREAM_TYPES, encoding: Optional[str] = None
) -> None:
- """append a file to search for similarities"""
+ """Append a file to search for similarities."""
if isinstance(stream, BufferedIOBase):
if encoding is None:
raise ValueError
@@ -395,13 +395,13 @@ class Similar:
pass
def run(self) -> None:
- """start looking for similarities and display results on stdout"""
+ """Start looking for similarities and display results on stdout."""
if self.min_lines == 0:
return
self._display_sims(self._compute_sims())
def _compute_sims(self) -> List[Tuple[int, Set[LinesChunkLimits_T]]]:
- """compute similarities in appended files"""
+ """Compute similarities in appended files."""
no_duplicates: Dict[int, List[Set[LinesChunkLimits_T]]] = defaultdict(list)
for commonality in self._iter_sims():
@@ -442,14 +442,14 @@ class Similar:
def _display_sims(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> None:
- """Display computed similarities on stdout"""
+ """Display computed similarities on stdout."""
report = self._get_similarity_report(similarities)
print(report)
def _get_similarity_report(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> str:
- """Create a report from similarities"""
+ """Create a report from similarities."""
report: str = ""
duplicated_line_number: int = 0
for number, couples in similarities:
@@ -535,7 +535,7 @@ class Similar:
yield com
def _iter_sims(self) -> Generator[Commonality, None, None]:
- """iterate on similarities among all files, by making a cartesian
+ """Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
@@ -543,7 +543,7 @@ class Similar:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
- """Returns the data we can use for a map/reduce process
+ """Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
@@ -551,7 +551,7 @@ class Similar:
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
- """Reduces and recombines data into a format that we can report on
+ """Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
@@ -565,7 +565,7 @@ def stripped_lines(
ignore_imports: bool,
ignore_signatures: bool,
) -> List[LineSpecifs]:
- """Return tuples of line/line number/line type with leading/trailing whitespace and any ignored code features removed
+ """Return tuples of line/line number/line type with leading/trailing whitespace and any ignored code features removed.
:param lines: a collection of lines
:param ignore_comments: if true, any comment in the lines collection is removed from the result
@@ -720,7 +720,7 @@ def report_similarities(
stats: LinterStats,
old_stats: Optional[LinterStats],
) -> None:
- """make a layout with some stats about duplication"""
+ """Make a layout with some stats about duplication."""
lines = ["", "now", "previous", "difference"]
lines += table_lines_from_stats(stats, old_stats, "duplicated_lines")
sect.append(Table(children=lines, cols=4, rheaders=1, cheaders=1))
@@ -728,7 +728,7 @@ def report_similarities(
# wrapper to get a pylint checker from the similar class
class SimilarChecker(BaseChecker, Similar, MapReduceMixin):
- """checks for similarities and duplicated code. This computation may be
+ """Checks for similarities and duplicated code. This computation may be
memory / CPU intensive, so you should disable it if you experiment some
problems.
"""
@@ -802,7 +802,7 @@ class SimilarChecker(BaseChecker, Similar, MapReduceMixin):
)
def set_option(self, optname, value, action=None, optdict=None):
- """method called to set an option (registered in the options list)
+ """Method called to set an option (registered in the options list).
Overridden to report options setting to Similar
"""
@@ -819,12 +819,12 @@ class SimilarChecker(BaseChecker, Similar, MapReduceMixin):
self.ignore_signatures = self.config.ignore_signatures
def open(self):
- """init the checkers: reset linesets and statistics information"""
+ """Init the checkers: reset linesets and statistics information."""
self.linesets = []
self.linter.stats.reset_duplicated_lines()
def process_module(self, node: nodes.Module) -> None:
- """process a module
+ """Process a module.
the module's content is accessible via the stream object
@@ -842,7 +842,7 @@ class SimilarChecker(BaseChecker, Similar, MapReduceMixin):
self.append_stream(self.linter.current_name, stream, node.file_encoding) # type: ignore[arg-type]
def close(self):
- """compute and display similarities on closing (i.e. end of parsing)"""
+ """Compute and display similarities on closing (i.e. end of parsing)."""
total = sum(len(lineset) for lineset in self.linesets)
duplicated = 0
stats = self.linter.stats
@@ -863,11 +863,11 @@ class SimilarChecker(BaseChecker, Similar, MapReduceMixin):
stats.percent_duplicated_lines += float(total and duplicated * 100.0 / total)
def get_map_data(self):
- """Passthru override"""
+ """Passthru override."""
return Similar.get_map_data(self)
def reduce_map_data(self, linter, data):
- """Reduces and recombines data into a format that we can report on
+ """Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
@@ -887,7 +887,7 @@ def register(linter: "PyLinter") -> None:
def usage(status=0):
- """display command line usage information"""
+ """Display command line usage information."""
print("finds copy pasted blocks in a set of files")
print()
print(
@@ -898,7 +898,7 @@ def usage(status=0):
def Run(argv=None):
- """standalone command line access point"""
+ """Standalone command line access point."""
if argv is None:
argv = sys.argv[1:]
diff --git a/pylint/checkers/spelling.py b/pylint/checkers/spelling.py
index 777153c64..8c004444e 100644
--- a/pylint/checkers/spelling.py
+++ b/pylint/checkers/spelling.py
@@ -146,7 +146,7 @@ class SphinxDirectives(RegExFilter):
class ForwardSlashChunker(Chunker):
- """This chunker allows splitting words like 'before/after' into 'before' and 'after'"""
+ """This chunker allows splitting words like 'before/after' into 'before' and 'after'."""
def next(self):
while True:
@@ -203,7 +203,7 @@ def _strip_code_flanked_in_backticks(line: str) -> str:
class SpellingChecker(BaseTokenChecker):
- """Check spelling in comments and docstrings"""
+ """Check spelling in comments and docstrings."""
__implements__ = (ITokenChecker, IAstroidChecker)
name = "spelling"
@@ -459,7 +459,7 @@ class SpellingChecker(BaseTokenChecker):
visit_asyncfunctiondef = visit_functiondef
def _check_docstring(self, node):
- """check the node has any spelling errors"""
+ """Check the node has any spelling errors."""
docstring = node.doc
if not docstring:
return
diff --git a/pylint/checkers/strings.py b/pylint/checkers/strings.py
index e512e457d..e89e8db5f 100644
--- a/pylint/checkers/strings.py
+++ b/pylint/checkers/strings.py
@@ -635,7 +635,7 @@ class StringFormatChecker(BaseChecker):
class StringConstantChecker(BaseTokenChecker):
- """Check string literals"""
+ """Check string literals."""
__implements__ = (IAstroidChecker, ITokenChecker, IRawChecker)
name = "string"
@@ -850,7 +850,7 @@ class StringConstantChecker(BaseTokenChecker):
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
- """check for bad escapes in a non-raw string.
+ """Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
@@ -917,7 +917,7 @@ class StringConstantChecker(BaseTokenChecker):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
- """Check whether strings include a 'u' prefix like u'String'"""
+ """Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
diff --git a/pylint/checkers/threading_checker.py b/pylint/checkers/threading_checker.py
index cedf46a9e..6148b8292 100644
--- a/pylint/checkers/threading_checker.py
+++ b/pylint/checkers/threading_checker.py
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
class ThreadingChecker(BaseChecker):
- """Checks for threading module
+ """Checks for threading module.
- useless with lock - locking used in wrong way that has no effect (with threading.Lock():)
"""
diff --git a/pylint/checkers/typecheck.py b/pylint/checkers/typecheck.py
index 825c38082..b28815e70 100644
--- a/pylint/checkers/typecheck.py
+++ b/pylint/checkers/typecheck.py
@@ -55,7 +55,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
-"""try to find more bugs in the code using astroid inference capabilities"""
+"""Try to find more bugs in the code using astroid inference capabilities."""
import fnmatch
import heapq
@@ -149,7 +149,7 @@ def _flatten_container(iterable):
def _is_owner_ignored(owner, attrname, ignored_classes, ignored_modules):
- """Check if the given owner should be ignored
+ """Check if the given owner should be ignored.
This will verify if the owner's module is in *ignored_modules*
or the owner's module fully qualified name is in *ignored_modules*
@@ -233,7 +233,7 @@ def _string_distance(seq1, seq2):
def _similar_names(owner, attrname, distance_threshold, max_choices):
- """Given an owner and a name, try to find similar names
+ """Given an owner and a name, try to find similar names.
The similar names are searched given a distance metric and only
a given number of choices will be returned.
@@ -664,7 +664,7 @@ def _no_context_variadic_positional(node, scope):
def _no_context_variadic(node, variadic_name, variadic_type, variadics):
- """Verify if the given call node has variadic nodes without context
+ """Verify if the given call node has variadic nodes without context.
This is a workaround for handling cases of nested call functions
which don't have the specific call context at hand.
@@ -722,7 +722,7 @@ def _is_invalid_metaclass(metaclass):
def _infer_from_metaclass_constructor(cls, func: nodes.FunctionDef):
- """Try to infer what the given *func* constructor is building
+ """Try to infer what the given *func* constructor is building.
:param astroid.FunctionDef func:
A metaclass constructor. Metaclass definitions can be
@@ -781,7 +781,7 @@ def _is_invalid_isinstance_type(arg):
class TypeChecker(BaseChecker):
- """try to find bugs in the code using type inference"""
+ """Try to find bugs in the code using type inference."""
__implements__ = (IAstroidChecker,)
@@ -1006,7 +1006,7 @@ accessed. Python regular expressions are accepted.",
@check_messages("no-member", "c-extension-no-member")
def visit_attribute(self, node: nodes.Attribute) -> None:
- """check that the accessed attribute exists
+ """Check that the accessed attribute exists.
to avoid too much false positives for now, we'll consider the code as
correct if a single of the inferred nodes has the accessed attribute.
@@ -1210,7 +1210,7 @@ accessed. Python regular expressions are accepted.",
)
def _check_dundername_is_string(self, node) -> None:
- """Check a string is assigned to self.__name__"""
+ """Check a string is assigned to self.__name__."""
# Check the left-hand side of the assignment is <something>.__name__
lhs = node.targets[0]
@@ -1331,7 +1331,7 @@ accessed. Python regular expressions are accepted.",
# pylint: disable=too-many-branches,too-many-locals
@check_messages(*(list(MSGS.keys())))
def visit_call(self, node: nodes.Call) -> None:
- """check that called functions/methods are inferred to callable objects,
+ """Check that called functions/methods are inferred to callable objects,
and that the arguments passed to the function match the parameters in
the inferred function's definition
"""
@@ -1644,7 +1644,7 @@ accessed. Python regular expressions are accepted.",
def _check_not_callable(
self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG]
) -> None:
- """Checks to see if the not-callable message should be emitted
+ """Checks to see if the not-callable message should be emitted.
Only functions, generators and objects defining __call__ are "callable"
We ignore instances of descriptors since astroid cannot properly handle them yet
diff --git a/pylint/checkers/unicode.py b/pylint/checkers/unicode.py
index 88b534dae..93dfacb4b 100644
--- a/pylint/checkers/unicode.py
+++ b/pylint/checkers/unicode.py
@@ -52,7 +52,7 @@ BIDI_UNICODE = [
class _BadChar(NamedTuple):
- """Representation of an ASCII char considered bad"""
+ """Representation of an ASCII char considered bad."""
name: str
unescaped: str
@@ -61,14 +61,14 @@ class _BadChar(NamedTuple):
help_text: str
def description(self) -> str:
- """Used for the detailed error message description"""
+ """Used for the detailed error message description."""
return (
f"Invalid unescaped character {self.name}, "
f'use "{self.escaped}" instead.'
)
def human_code(self) -> str:
- """Used to generate the human readable error message"""
+ """Used to generate the human readable error message."""
return f"invalid-character-{self.name}"
@@ -135,7 +135,7 @@ BAD_ASCII_SEARCH_DICT = {char.unescaped: char for char in BAD_CHARS}
def _line_length(line: _StrLike, codec: str) -> int:
- """Get the length of a string like line as displayed in an editor"""
+ """Get the length of a string like line as displayed in an editor."""
if isinstance(line, bytes):
decoded = _remove_bom(line, codec).decode(codec, "replace")
else:
@@ -155,7 +155,7 @@ def _map_positions_to_result(
new_line: _StrLike,
byte_str_length: int = 1,
) -> Dict[int, _BadChar]:
- """Get all occurrences of search dict keys within line
+ """Get all occurrences of search dict keys within line.
Ignores Windows end of line and can handle bytes as well as string.
Also takes care of encodings for which the length of an encoded code point does not
@@ -208,12 +208,12 @@ UTF_NAME_REGEX_COMPILED = re.compile(
def _normalize_codec_name(codec: str) -> str:
- """Make sure the codec name is always given as defined in the BOM dict"""
+ """Make sure the codec name is always given as defined in the BOM dict."""
return UTF_NAME_REGEX_COMPILED.sub(r"utf-\1\2", codec).lower()
def _remove_bom(encoded: bytes, encoding: str) -> bytes:
- """remove the bom if given from a line"""
+ """Remove the bom if given from a line."""
if not encoding.startswith("utf"):
return encoded
bom = UNICODE_BOMS[encoding]
@@ -223,12 +223,12 @@ def _remove_bom(encoded: bytes, encoding: str) -> bytes:
def _encode_without_bom(string: str, encoding: str) -> bytes:
- """Encode a string but remove the BOM"""
+ """Encode a string but remove the BOM."""
return _remove_bom(string.encode(encoding), encoding)
def _byte_to_str_length(codec: str) -> int:
- """return how many byte are usually(!) a character point"""
+ """Return how many byte are usually(!) a character point."""
if codec.startswith("utf-32"):
return 4
if codec.startswith("utf-16"):
@@ -239,12 +239,12 @@ def _byte_to_str_length(codec: str) -> int:
@lru_cache(maxsize=1000)
def _cached_encode_search(string: str, encoding: str) -> bytes:
- """A cached version of encode used for search pattern"""
+ """A cached version of encode used for search pattern."""
return _encode_without_bom(string, encoding)
def _fix_utf16_32_line_stream(steam: Iterable[bytes], codec: str) -> Iterable[bytes]:
- """Handle line ending for UTF16 and UTF32 correctly
+ """Handle line ending for UTF16 and UTF32 correctly.
Currently Python simply strips the required zeros after \n after the
line ending. Leading to lines that can't be decoded propery
@@ -274,7 +274,7 @@ def _fix_utf16_32_line_stream(steam: Iterable[bytes], codec: str) -> Iterable[by
def extract_codec_from_bom(first_line: bytes) -> str:
- """Try to extract the codec (unicode only) by checking for the BOM
+ """Try to extract the codec (unicode only) by checking for the BOM.
For details about BOM see https://unicode.org/faq/utf_bom.html#BOM
@@ -295,7 +295,7 @@ def extract_codec_from_bom(first_line: bytes) -> str:
class UnicodeChecker(pylint.checkers.BaseChecker):
- """Check characters that could be used to hide bad code to humans
+ """Check characters that could be used to hide bad code to humans.
This includes:
@@ -381,7 +381,7 @@ class UnicodeChecker(pylint.checkers.BaseChecker):
@classmethod
def _find_line_matches(cls, line: bytes, codec: str) -> Dict[int, _BadChar]:
- """Find all matches of BAD_CHARS within line
+ """Find all matches of BAD_CHARS within line.
Args:
line: the input
@@ -417,7 +417,7 @@ class UnicodeChecker(pylint.checkers.BaseChecker):
@staticmethod
def _determine_codec(stream: io.BytesIO) -> Tuple[str, int]:
- """determine the codec from the given stream
+ """Determine the codec from the given stream.
first tries https://www.python.org/dev/peps/pep-0263/
and if this fails also checks for BOMs of UTF-16 and UTF-32
@@ -457,7 +457,7 @@ class UnicodeChecker(pylint.checkers.BaseChecker):
return _normalize_codec_name(codec), codec_definition_line
def _check_codec(self, codec: str, codec_definition_line: int) -> None:
- """Check validity of the codec"""
+ """Check validity of the codec."""
if codec != "utf-8":
msg = "bad-file-encoding"
if self._is_invalid_codec(codec):
@@ -474,7 +474,7 @@ class UnicodeChecker(pylint.checkers.BaseChecker):
)
def _check_invalid_chars(self, line: bytes, lineno: int, codec: str) -> None:
- """Look for chars considered bad"""
+ """Look for chars considered bad."""
matches = self._find_line_matches(line, codec)
for col, char in matches.items():
self.add_message(
@@ -489,7 +489,7 @@ class UnicodeChecker(pylint.checkers.BaseChecker):
)
def _check_bidi_chars(self, line: bytes, lineno: int, codec: str) -> None:
- """Look for Bidirectional Unicode, if we use unicode"""
+ """Look for Bidirectional Unicode, if we use unicode."""
if not self._is_unicode(codec):
return
for dangerous in BIDI_UNICODE:
diff --git a/pylint/checkers/unsupported_version.py b/pylint/checkers/unsupported_version.py
index ada104ab9..b3369b877 100644
--- a/pylint/checkers/unsupported_version.py
+++ b/pylint/checkers/unsupported_version.py
@@ -57,13 +57,13 @@ class UnsupportedVersionChecker(BaseChecker):
@check_messages("using-f-string-in-unsupported-version")
def visit_joinedstr(self, node: nodes.JoinedStr) -> None:
- """Check f-strings"""
+ """Check f-strings."""
if not self._py36_plus:
self.add_message("using-f-string-in-unsupported-version", node=node)
@check_messages("using-final-decorator-in-unsupported-version")
def visit_decorators(self, node: nodes.Decorators) -> None:
- """Check decorators"""
+ """Check decorators."""
self._check_typing_final(node)
def _check_typing_final(self, node: nodes.Decorators) -> None:
diff --git a/pylint/checkers/utils.py b/pylint/checkers/utils.py
index f34faecc8..026a78b5e 100644
--- a/pylint/checkers/utils.py
+++ b/pylint/checkers/utils.py
@@ -57,7 +57,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
-"""some functions that may be useful for various checkers"""
+"""Some functions that may be useful for various checkers."""
import builtins
import itertools
import numbers
@@ -293,7 +293,7 @@ class InferredTypeError(Exception):
def is_inside_lambda(node: nodes.NodeNG) -> bool:
- """Return whether the given node is inside a lambda"""
+ """Return whether the given node is inside a lambda."""
warnings.warn(
"utils.is_inside_lambda will be removed in favour of calling "
"utils.get_node_first_ancestor_of_type(x, nodes.Lambda) in pylint 3.0",
@@ -314,14 +314,14 @@ def get_all_elements(
def is_super(node: nodes.NodeNG) -> bool:
- """return True if the node is referencing the "super" builtin function"""
+ """Return True if the node is referencing the "super" builtin function."""
if getattr(node, "name", None) == "super" and node.root().name == "builtins":
return True
return False
def is_error(node: nodes.FunctionDef) -> bool:
- """Return true if the given function node only raises an exception"""
+ """Return true if the given function node only raises an exception."""
return len(node.body) == 1 and isinstance(node.body[0], nodes.Raise)
@@ -335,7 +335,7 @@ def is_builtin_object(node: nodes.NodeNG) -> bool:
def is_builtin(name: str) -> bool:
- """return true if <name> could be considered as a builtin defined by python"""
+ """Return true if <name> could be considered as a builtin defined by python."""
return name in builtins or name in SPECIAL_BUILTINS # type: ignore[attr-defined]
@@ -388,7 +388,7 @@ def is_defined_in_scope(
def is_defined_before(var_node: nodes.Name) -> bool:
- """Check if the given variable node is defined before
+ """Check if the given variable node is defined before.
Verify that the variable node is defined by a parent node
(list, set, dict, or generator comprehension, lambda)
@@ -417,7 +417,7 @@ def is_defined_before(var_node: nodes.Name) -> bool:
def is_default_argument(
node: nodes.NodeNG, scope: Optional[nodes.NodeNG] = None
) -> bool:
- """return true if the given Name node is used in function or lambda
+ """Return true if the given Name node is used in function or lambda
default argument's value
"""
if not scope:
@@ -436,7 +436,7 @@ def is_default_argument(
def is_func_decorator(node: nodes.NodeNG) -> bool:
- """return true if the name is used in function decorator"""
+ """Return true if the name is used in function decorator."""
for parent in node.node_ancestors():
if isinstance(parent, nodes.Decorators):
return True
@@ -453,7 +453,7 @@ def is_func_decorator(node: nodes.NodeNG) -> bool:
def is_ancestor_name(frame: nodes.ClassDef, node: nodes.NodeNG) -> bool:
- """return whether `frame` is an astroid.Class node with `node` in the
+ """Return whether `frame` is an astroid.Class node with `node` in the
subtree of its bases attribute
"""
if not isinstance(frame, nodes.ClassDef):
@@ -462,19 +462,19 @@ def is_ancestor_name(frame: nodes.ClassDef, node: nodes.NodeNG) -> bool:
def is_being_called(node: nodes.NodeNG) -> bool:
- """return True if node is the function being called in a Call node"""
+ """Return True if node is the function being called in a Call node."""
return isinstance(node.parent, nodes.Call) and node.parent.func is node
def assign_parent(node: nodes.NodeNG) -> nodes.NodeNG:
- """return the higher parent which is not an AssignName, Tuple or List node"""
+ """Return the higher parent which is not an AssignName, Tuple or List node."""
while node and isinstance(node, (nodes.AssignName, nodes.Tuple, nodes.List)):
node = node.parent
return node
def overrides_a_method(class_node: nodes.ClassDef, name: str) -> bool:
- """return True if <name> is a method overridden from an ancestor
+ """Return True if <name> is a method overridden from an ancestor
which is not the base object class
"""
for ancestor in class_node.ancestors():
@@ -486,7 +486,7 @@ def overrides_a_method(class_node: nodes.ClassDef, name: str) -> bool:
def check_messages(*messages: str) -> Callable:
- """decorator to store messages that are handled by a checker method"""
+ """Decorator to store messages that are handled by a checker method."""
def store_messages(func):
func.checks_msgs = messages
@@ -652,7 +652,7 @@ def parse_format_method_string(
def is_attr_protected(attrname: str) -> bool:
- """return True if attribute name is protected (start with _ and some other
+ """Return True if attribute name is protected (start with _ and some other
details), False otherwise.
"""
return (
@@ -663,7 +663,7 @@ def is_attr_protected(attrname: str) -> bool:
def node_frame_class(node: nodes.NodeNG) -> Optional[nodes.ClassDef]:
- """Return the class that is wrapping the given node
+ """Return the class that is wrapping the given node.
The function returns a class for a method node (or a staticmethod or a
classmethod), otherwise it returns `None`.
@@ -688,7 +688,7 @@ def node_frame_class(node: nodes.NodeNG) -> Optional[nodes.ClassDef]:
def get_outer_class(class_node: astroid.ClassDef) -> Optional[astroid.ClassDef]:
- """Return the class that is the outer class of given (nested) class_node"""
+ """Return the class that is the outer class of given (nested) class_node."""
parent_klass = class_node.parent.frame(future=True)
return parent_klass if isinstance(parent_klass, astroid.ClassDef) else None
@@ -792,17 +792,17 @@ def _is_property_kind(node, *kinds):
def is_property_setter(node: nodes.FunctionDef) -> bool:
- """Check if the given node is a property setter"""
+ """Check if the given node is a property setter."""
return _is_property_kind(node, "setter")
def is_property_deleter(node: nodes.FunctionDef) -> bool:
- """Check if the given node is a property deleter"""
+ """Check if the given node is a property deleter."""
return _is_property_kind(node, "deleter")
def is_property_setter_or_deleter(node: nodes.FunctionDef) -> bool:
- """Check if the given node is either a property setter or a deleter"""
+ """Check if the given node is either a property setter or a deleter."""
return _is_property_kind(node, "setter", "deleter")
@@ -1071,7 +1071,7 @@ def node_ignores_exception(node: nodes.NodeNG, exception=Exception) -> bool:
def class_is_abstract(node: nodes.ClassDef) -> bool:
- """return true if the given class node should be considered as an abstract
+ """Return true if the given class node should be considered as an abstract
class
"""
# Only check for explicit metaclass=ABCMeta on this specific class
@@ -1313,7 +1313,7 @@ def is_none(node: nodes.NodeNG) -> bool:
def node_type(node: nodes.NodeNG) -> Optional[nodes.NodeNG]:
- """Return the inferred type for `node`
+ """Return the inferred type for `node`.
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
@@ -1388,7 +1388,7 @@ def get_node_last_lineno(node: nodes.NodeNG) -> int:
def is_postponed_evaluation_enabled(node: nodes.NodeNG) -> bool:
- """Check if the postponed evaluation of annotations is enabled"""
+ """Check if the postponed evaluation of annotations is enabled."""
module = node.root()
return "annotations" in module.future_imports
@@ -1466,7 +1466,7 @@ def is_overload_stub(node: nodes.NodeNG) -> bool:
def is_protocol_class(cls: nodes.NodeNG) -> bool:
- """Check if the given node represents a protocol class
+ """Check if the given node represents a protocol class.
:param cls: The node to check
:returns: True if the node is a typing protocol class, false otherwise.
@@ -1480,7 +1480,7 @@ def is_protocol_class(cls: nodes.NodeNG) -> bool:
def is_call_of_name(node: nodes.NodeNG, name: str) -> bool:
- """Checks if node is a function call with the given name"""
+ """Checks if node is a function call with the given name."""
return (
isinstance(node, nodes.Call)
and isinstance(node.func, nodes.Name)
@@ -1492,7 +1492,7 @@ def is_test_condition(
node: nodes.NodeNG,
parent: Optional[nodes.NodeNG] = None,
) -> bool:
- """Returns true if the given node is being tested for truthiness"""
+ """Returns true if the given node is being tested for truthiness."""
parent = parent or node.parent
if isinstance(parent, (nodes.While, nodes.If, nodes.IfExp, nodes.Assert)):
return node is parent.test or parent.test.parent_of(node)
@@ -1600,7 +1600,7 @@ def get_subscript_const_value(node: nodes.Subscript) -> nodes.Const:
def get_import_name(
importnode: Union[nodes.Import, nodes.ImportFrom], modname: str
) -> str:
- """Get a prepared module name from the given import node
+ """Get a prepared module name from the given import node.
In the case of relative imports, this will return the
absolute qualified module name, which might be useful
@@ -1666,7 +1666,7 @@ def is_node_in_guarded_import_block(node: nodes.NodeNG) -> bool:
def is_reassigned_after_current(node: nodes.NodeNG, varname: str) -> bool:
- """Check if the given variable name is reassigned in the same scope after the current node"""
+ """Check if the given variable name is reassigned in the same scope after the current node."""
return any(
a.name == varname and a.lineno > node.lineno
for a in node.scope().nodes_of_class(
@@ -1676,7 +1676,7 @@ def is_reassigned_after_current(node: nodes.NodeNG, varname: str) -> bool:
def is_deleted_after_current(node: nodes.NodeNG, varname: str) -> bool:
- """Check if the given variable name is deleted in the same scope after the current node"""
+ """Check if the given variable name is deleted in the same scope after the current node."""
return any(
getattr(target, "name", None) == varname and target.lineno > node.lineno
for del_node in node.scope().nodes_of_class(nodes.Delete)
@@ -1685,7 +1685,7 @@ def is_deleted_after_current(node: nodes.NodeNG, varname: str) -> bool:
def is_function_body_ellipsis(node: nodes.FunctionDef) -> bool:
- """Checks whether a function body only consists of a single Ellipsis"""
+ """Checks whether a function body only consists of a single Ellipsis."""
return (
len(node.body) == 1
and isinstance(node.body[0], nodes.Expr)
@@ -1709,7 +1709,7 @@ def is_empty_str_literal(node: Optional[nodes.NodeNG]) -> bool:
def returns_bool(node: nodes.NodeNG) -> bool:
- """Returns true if a node is a return that returns a constant boolean"""
+ """Returns true if a node is a return that returns a constant boolean."""
return (
isinstance(node, nodes.Return)
and isinstance(node.value, nodes.Const)
@@ -1720,7 +1720,7 @@ def returns_bool(node: nodes.NodeNG) -> bool:
def get_node_first_ancestor_of_type(
node: nodes.NodeNG, ancestor_type: Union[Type[T_Node], Tuple[Type[T_Node], ...]]
) -> Optional[T_Node]:
- """Return the first parent node that is any of the provided types (or None)"""
+ """Return the first parent node that is any of the provided types (or None)."""
for ancestor in node.node_ancestors():
if isinstance(ancestor, ancestor_type):
return ancestor
diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py
index 160680caa..90eee481f 100644
--- a/pylint/checkers/variables.py
+++ b/pylint/checkers/variables.py
@@ -54,7 +54,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
-"""Variables checkers for Python code"""
+"""Variables checkers for Python code."""
import collections
import copy
import itertools
@@ -197,7 +197,7 @@ def in_for_else_branch(parent, stmt):
@lru_cache(maxsize=1000)
def overridden_method(klass, name):
- """get overridden method if any"""
+ """Get overridden method if any."""
try:
parent = next(klass.local_attr_ancestors(name))
except (StopIteration, KeyError):
@@ -214,7 +214,7 @@ def overridden_method(klass, name):
def _get_unpacking_extra_info(node, inferred):
- """return extra information to add to the message for unpacking-non-sequence
+ """Return extra information to add to the message for unpacking-non-sequence
and unbalanced-tuple-unpacking errors
"""
more = ""
@@ -378,13 +378,13 @@ def _flattened_scope_names(iterator):
def _assigned_locally(name_node):
- """Checks if name_node has corresponding assign statement in same scope"""
+ """Checks if name_node has corresponding assign statement in same scope."""
assign_stmts = name_node.scope().nodes_of_class(nodes.AssignName)
return any(a.name == name_node.name for a in assign_stmts)
def _is_type_checking_import(node: Union[nodes.Import, nodes.ImportFrom]) -> bool:
- """Check if an import node is guarded by a TYPE_CHECKS guard"""
+ """Check if an import node is guarded by a TYPE_CHECKS guard."""
return any(
isinstance(ancestor, nodes.If)
and ancestor.test.as_string() in TYPING_TYPE_CHECKS_GUARDS
@@ -556,7 +556,7 @@ class ScopeConsumer(NamedTuple):
class NamesConsumer:
- """A simple class to handle consumed, to consume and scope type info of node locals"""
+ """A simple class to handle consumed, to consume and scope type info of node locals."""
def __init__(self, node, scope_type):
self._atomic = ScopeConsumer(
@@ -981,7 +981,7 @@ scope_type : {self._atomic.scope_type}
# pylint: disable=too-many-public-methods
class VariablesChecker(BaseChecker):
- """checks for
+ """Checks for
* unused variables / imports
* undefined variables
* redefinition of variable from builtins or from an outer scope
@@ -1093,11 +1093,11 @@ class VariablesChecker(BaseChecker):
self._except_handler_names_queue: List[
Tuple[nodes.ExceptHandler, nodes.AssignName]
] = []
- """This is a queue, last in first out"""
+ """This is a queue, last in first out."""
self._postponed_evaluation_enabled = False
def open(self) -> None:
- """Called when loading the checker"""
+ """Called when loading the checker."""
self._is_undefined_variable_enabled = self.linter.is_message_enabled(
"undefined-variable"
)
@@ -1136,7 +1136,7 @@ class VariablesChecker(BaseChecker):
self._store_type_annotation_names(node)
def visit_module(self, node: nodes.Module) -> None:
- """visit module : update consumption analysis variable
+ """Visit module : update consumption analysis variable
checks globals doesn't overrides builtins
"""
self._to_consume = [NamesConsumer(node, "module")]
@@ -1158,7 +1158,7 @@ class VariablesChecker(BaseChecker):
"unused-variable",
)
def leave_module(self, node: nodes.Module) -> None:
- """leave module: check globals"""
+ """Leave module: check globals."""
assert len(self._to_consume) == 1
self._check_metaclasses(node)
@@ -1177,52 +1177,52 @@ class VariablesChecker(BaseChecker):
self._check_imports(not_consumed)
def visit_classdef(self, node: nodes.ClassDef) -> None:
- """visit class: update consumption analysis variable"""
+ """Visit class: update consumption analysis variable."""
self._to_consume.append(NamesConsumer(node, "class"))
def leave_classdef(self, _: nodes.ClassDef) -> None:
- """leave class: update consumption analysis variable"""
+ """Leave class: update consumption analysis variable."""
# do not check for not used locals here (no sense)
self._to_consume.pop()
def visit_lambda(self, node: nodes.Lambda) -> None:
- """visit lambda: update consumption analysis variable"""
+ """Visit lambda: update consumption analysis variable."""
self._to_consume.append(NamesConsumer(node, "lambda"))
def leave_lambda(self, _: nodes.Lambda) -> None:
- """leave lambda: update consumption analysis variable"""
+ """Leave lambda: update consumption analysis variable."""
# do not check for not used locals here
self._to_consume.pop()
def visit_generatorexp(self, node: nodes.GeneratorExp) -> None:
- """visit genexpr: update consumption analysis variable"""
+ """Visit genexpr: update consumption analysis variable."""
self._to_consume.append(NamesConsumer(node, "comprehension"))
def leave_generatorexp(self, _: nodes.GeneratorExp) -> None:
- """leave genexpr: update consumption analysis variable"""
+ """Leave genexpr: update consumption analysis variable."""
# do not check for not used locals here
self._to_consume.pop()
def visit_dictcomp(self, node: nodes.DictComp) -> None:
- """visit dictcomp: update consumption analysis variable"""
+ """Visit dictcomp: update consumption analysis variable."""
self._to_consume.append(NamesConsumer(node, "comprehension"))
def leave_dictcomp(self, _: nodes.DictComp) -> None:
- """leave dictcomp: update consumption analysis variable"""
+ """Leave dictcomp: update consumption analysis variable."""
# do not check for not used locals here
self._to_consume.pop()
def visit_setcomp(self, node: nodes.SetComp) -> None:
- """visit setcomp: update consumption analysis variable"""
+ """Visit setcomp: update consumption analysis variable."""
self._to_consume.append(NamesConsumer(node, "comprehension"))
def leave_setcomp(self, _: nodes.SetComp) -> None:
- """leave setcomp: update consumption analysis variable"""
+ """Leave setcomp: update consumption analysis variable."""
# do not check for not used locals here
self._to_consume.pop()
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
- """visit function: update consumption analysis variable and check locals"""
+ """Visit function: update consumption analysis variable and check locals."""
self._to_consume.append(NamesConsumer(node, "function"))
if not (
self.linter.is_message_enabled("redefined-outer-name")
@@ -1264,7 +1264,7 @@ class VariablesChecker(BaseChecker):
self.add_message("redefined-builtin", args=name, node=stmt)
def leave_functiondef(self, node: nodes.FunctionDef) -> None:
- """leave function: check function's locals are consumed"""
+ """Leave function: check function's locals are consumed."""
self._check_metaclasses(node)
if node.type_comment_returns:
@@ -1306,7 +1306,7 @@ class VariablesChecker(BaseChecker):
"redefined-builtin",
)
def visit_global(self, node: nodes.Global) -> None:
- """check names imported exists in the global scope"""
+ """Check names imported exists in the global scope."""
frame = node.frame(future=True)
if isinstance(frame, nodes.Module):
self.add_message("global-at-module-level", node=node)
@@ -1502,7 +1502,7 @@ class VariablesChecker(BaseChecker):
consumer_level: int,
base_scope_type: Any,
) -> Tuple[VariableVisitConsumerAction, Optional[List[nodes.NodeNG]]]:
- """Checks a consumer for conditions that should trigger messages"""
+ """Checks a consumer for conditions that should trigger messages."""
# If the name has already been consumed, only check it's not a loop
# variable used outside the loop.
# Avoid the case where there are homonyms inside function scope and
@@ -1719,7 +1719,7 @@ class VariablesChecker(BaseChecker):
@utils.check_messages("no-name-in-module")
def visit_import(self, node: nodes.Import) -> None:
- """check modules attribute accesses"""
+ """Check modules attribute accesses."""
if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
# No need to verify this, since ImportError is already
# handled by the client code.
@@ -1741,7 +1741,7 @@ class VariablesChecker(BaseChecker):
@utils.check_messages("no-name-in-module")
def visit_importfrom(self, node: nodes.ImportFrom) -> None:
- """check modules attribute accesses"""
+ """Check modules attribute accesses."""
if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
# No need to verify this, since ImportError is already
# handled by the client code.
@@ -1786,11 +1786,11 @@ class VariablesChecker(BaseChecker):
# listcomp have now also their scope
def visit_listcomp(self, node: nodes.ListComp) -> None:
- """visit dictcomp: update consumption analysis variable"""
+ """Visit dictcomp: update consumption analysis variable."""
self._to_consume.append(NamesConsumer(node, "comprehension"))
def leave_listcomp(self, _: nodes.ListComp) -> None:
- """leave dictcomp: update consumption analysis variable"""
+ """Leave dictcomp: update consumption analysis variable."""
# do not check for not used locals here
self._to_consume.pop()
@@ -1845,7 +1845,7 @@ class VariablesChecker(BaseChecker):
def _in_lambda_or_comprehension_body(
node: nodes.NodeNG, frame: nodes.NodeNG
) -> bool:
- """return True if node within a lambda/comprehension body (or similar) and thus should not have access to class attributes in frame"""
+ """Return True if node within a lambda/comprehension body (or similar) and thus should not have access to class attributes in frame."""
child = node
parent = node.parent
while parent is not None:
@@ -2076,7 +2076,7 @@ class VariablesChecker(BaseChecker):
@staticmethod
def _is_only_type_assignment(node: nodes.Name, defstmt: nodes.Statement) -> bool:
- """Check if variable only gets assigned a type and never a value"""
+ """Check if variable only gets assigned a type and never a value."""
if not isinstance(defstmt, nodes.AnnAssign) or defstmt.value:
return False
@@ -2487,7 +2487,7 @@ class VariablesChecker(BaseChecker):
)
def _store_type_annotation_node(self, type_annotation):
- """Given a type annotation, store all the name nodes it refers to"""
+ """Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
@@ -2518,7 +2518,7 @@ class VariablesChecker(BaseChecker):
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
- """Check that self/cls don't get assigned"""
+ """Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
@@ -2591,7 +2591,7 @@ class VariablesChecker(BaseChecker):
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
- """Return the list of values of the `Assign` node"""
+ """Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
@@ -2601,7 +2601,7 @@ class VariablesChecker(BaseChecker):
return None
def _check_module_attrs(self, node, module, module_names):
- """check that module_names (list of string) are accessible through the
+ """Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
diff --git a/pylint/config/find_default_config_files.py b/pylint/config/find_default_config_files.py
index 36fd351f0..10c31345d 100644
--- a/pylint/config/find_default_config_files.py
+++ b/pylint/config/find_default_config_files.py
@@ -71,7 +71,7 @@ def find_default_config_files() -> Iterator[str]:
def find_pylintrc() -> Optional[str]:
- """Search the pylint rc file and return its path if it finds it, else return None"""
+ """Search the pylint rc file and return its path if it finds it, else return None."""
for config_file in find_default_config_files():
if config_file.endswith("pylintrc"):
return config_file
diff --git a/pylint/config/man_help_formatter.py b/pylint/config/man_help_formatter.py
index e8e019824..c00f45468 100644
--- a/pylint/config/man_help_formatter.py
+++ b/pylint/config/man_help_formatter.py
@@ -107,7 +107,7 @@ Please report bugs on the project\'s mailing list:
return tail
def format_usage(self, usage):
- """Taken from optparse.IndentedHelpFormatter"""
+ """Taken from optparse.IndentedHelpFormatter."""
return f"Usage: {usage}\n"
diff --git a/pylint/config/option.py b/pylint/config/option.py
index 61384b8d4..cf88e3fc9 100644
--- a/pylint/config/option.py
+++ b/pylint/config/option.py
@@ -128,7 +128,7 @@ def _call_validator(opttype, optdict, option, value):
def _validate(value, optdict, name=""):
- """return a validated value for an option according to its type
+ """Return a validated value for an option according to its type.
optional argument name is only used for error message formatting
"""
diff --git a/pylint/config/option_manager_mixin.py b/pylint/config/option_manager_mixin.py
index 67740d334..9260f7593 100644
--- a/pylint/config/option_manager_mixin.py
+++ b/pylint/config/option_manager_mixin.py
@@ -23,7 +23,7 @@ from pylint.config.option_parser import OptionParser
def _expand_default(self, option):
- """Patch OptionParser.expand_default with custom behaviour
+ """Patch OptionParser.expand_default with custom behaviour.
This will handle defaults to avoid overriding values in the
configuration file.
@@ -57,7 +57,7 @@ def _patch_optparse():
class OptionsManagerMixIn:
- """Handle configuration from both a configuration file and command line options"""
+ """Handle configuration from both a configuration file and command line options."""
def __init__(self, usage, config_file=None):
self.config_file = config_file
@@ -83,7 +83,7 @@ class OptionsManagerMixIn:
self._optik_option_attrs = set(self.cmdline_parser.option_class.ATTRS)
def register_options_provider(self, provider, own_group=True):
- """register an options provider"""
+ """Register an options provider."""
assert provider.priority <= 0, "provider's priority can't be >= 0"
for i, options_provider in enumerate(self.options_providers):
if provider.priority > options_provider.priority:
@@ -142,7 +142,7 @@ class OptionsManagerMixIn:
self._maxlevel = max(self._maxlevel, option.level or 0)
def optik_option(self, provider, opt, optdict):
- """get our personal option definition and return a suitable form for
+ """Get our personal option definition and return a suitable form for
use with optik/optparse
"""
optdict = copy.copy(optdict)
@@ -173,7 +173,7 @@ class OptionsManagerMixIn:
return args, optdict
def cb_set_provider_option(self, option, opt, value, parser):
- """optik callback for option setting"""
+ """Optik callback for option setting."""
if opt.startswith("--"):
# remove -- on long option
opt = opt[2:]
@@ -186,13 +186,13 @@ class OptionsManagerMixIn:
self.global_set_option(opt, value)
def global_set_option(self, opt, value):
- """set option on the correct option provider"""
+ """Set option on the correct option provider."""
self._all_options[opt].set_option(opt, value)
def generate_config(
self, stream: Optional[TextIO] = None, skipsections: Tuple[str, ...] = ()
) -> None:
- """write a configuration file according to the current configuration
+ """Write a configuration file according to the current configuration
into the given stream or stdout
"""
options_by_section: Dict[str, List[Tuple]] = {}
@@ -239,7 +239,7 @@ class OptionsManagerMixIn:
print(formatter.format_tail(pkginfo), file=stream)
def load_provider_defaults(self):
- """initialize configuration using default values"""
+ """Initialize configuration using default values."""
for provider in self.options_providers:
provider.load_defaults()
@@ -343,7 +343,7 @@ class OptionsManagerMixIn:
continue
def load_configuration(self, **kwargs):
- """override configuration according to given parameters"""
+ """Override configuration according to given parameters."""
return self.load_configuration_from_config(kwargs)
def load_configuration_from_config(self, config):
@@ -353,7 +353,7 @@ class OptionsManagerMixIn:
provider.set_option(opt, opt_value)
def load_command_line_configuration(self, args=None) -> List[str]:
- """Override configuration according to command line parameters
+ """Override configuration according to command line parameters.
return additional arguments
"""
@@ -370,7 +370,7 @@ class OptionsManagerMixIn:
return args
def add_help_section(self, title, description, level=0):
- """add a dummy option section for help purpose"""
+ """Add a dummy option section for help purpose."""
group = optparse.OptionGroup(
self.cmdline_parser, title=title.capitalize(), description=description
)
@@ -379,7 +379,7 @@ class OptionsManagerMixIn:
self.cmdline_parser.add_option_group(group)
def help(self, level=0):
- """return the usage string for available options"""
+ """Return the usage string for available options."""
self.cmdline_parser.formatter.output_level = level
with _patch_optparse():
return self.cmdline_parser.format_help()
diff --git a/pylint/config/options_provider_mixin.py b/pylint/config/options_provider_mixin.py
index d3872135c..8c6204586 100644
--- a/pylint/config/options_provider_mixin.py
+++ b/pylint/config/options_provider_mixin.py
@@ -9,11 +9,11 @@ from pylint.config.option import _validate
class UnsupportedAction(Exception):
- """raised by set_option when it doesn't know what to do for an action"""
+ """Raised by set_option when it doesn't know what to do for an action."""
class OptionsProviderMixIn:
- """Mixin to provide options to an OptionsManager"""
+ """Mixin to provide options to an OptionsManager."""
# those attributes should be overridden
priority = -1
@@ -26,7 +26,7 @@ class OptionsProviderMixIn:
self.load_defaults()
def load_defaults(self):
- """initialize the provider using default values"""
+ """Initialize the provider using default values."""
for opt, optdict in self.options:
action = optdict.get("action")
if action != "callback":
@@ -37,17 +37,17 @@ class OptionsProviderMixIn:
self.set_option(opt, default, action, optdict)
def option_attrname(self, opt, optdict=None):
- """get the config attribute corresponding to opt"""
+ """Get the config attribute corresponding to opt."""
if optdict is None:
optdict = self.get_option_def(opt)
return optdict.get("dest", opt.replace("-", "_"))
def option_value(self, opt):
- """get the current value for the given option"""
+ """Get the current value for the given option."""
return getattr(self.config, self.option_attrname(opt), None)
def set_option(self, optname, value, action=None, optdict=None):
- """method called to set an option (registered in the options list)"""
+ """Method called to set an option (registered in the options list)."""
if optdict is None:
optdict = self.get_option_def(optname)
if value is not None:
@@ -80,7 +80,7 @@ class OptionsProviderMixIn:
raise UnsupportedAction(action)
def get_option_def(self, opt):
- """return the dictionary defining an option given its name"""
+ """Return the dictionary defining an option given its name."""
assert self.options
for option in self.options:
if option[0] == opt:
@@ -90,7 +90,7 @@ class OptionsProviderMixIn:
)
def options_by_section(self):
- """return an iterator on options grouped by section
+ """Return an iterator on options grouped by section.
(section, [list of (optname, optdict, optvalue)])
"""
diff --git a/pylint/epylint.py b/pylint/epylint.py
index 5517543a4..223f723a7 100755
--- a/pylint/epylint.py
+++ b/pylint/epylint.py
@@ -138,7 +138,7 @@ def lint(filename, options=()):
def py_run(command_options="", return_std=False, stdout=None, stderr=None):
- """Run pylint from python
+ """Run pylint from python.
``command_options`` is a string containing ``pylint`` command line options;
``return_std`` (boolean) indicates return of created standard output
diff --git a/pylint/exceptions.py b/pylint/exceptions.py
index ec1e513f7..5999dcfd4 100644
--- a/pylint/exceptions.py
+++ b/pylint/exceptions.py
@@ -16,24 +16,24 @@
class InvalidMessageError(Exception):
- """raised when a message creation, registration or addition is rejected"""
+ """Raised when a message creation, registration or addition is rejected."""
class UnknownMessageError(Exception):
- """raised when an unregistered message id is encountered"""
+ """Raised when an unregistered message id is encountered."""
class EmptyReportError(Exception):
- """raised when a report is empty and so should not be displayed"""
+ """Raised when a report is empty and so should not be displayed."""
class InvalidReporterError(Exception):
- """raised when selected reporter is invalid (e.g. not found)"""
+ """Raised when selected reporter is invalid (e.g. not found)."""
class InvalidArgsError(ValueError):
- """raised when passed arguments are invalid, e.g., have the wrong length"""
+ """Raised when passed arguments are invalid, e.g., have the wrong length."""
class NoLineSuppliedError(Exception):
- """raised when trying to disable a message on a next line without supplying a line number"""
+ """Raised when trying to disable a message on a next line without supplying a line number."""
diff --git a/pylint/extensions/__init__.py b/pylint/extensions/__init__.py
index 8b5fa9132..c34836101 100644
--- a/pylint/extensions/__init__.py
+++ b/pylint/extensions/__init__.py
@@ -10,7 +10,7 @@ if TYPE_CHECKING:
def initialize(linter: "PyLinter") -> None:
- """Initialize linter with checkers in the extensions directory"""
+ """Initialize linter with checkers in the extensions directory."""
register_plugins(linter, __path__[0])
diff --git a/pylint/extensions/_check_docs_utils.py b/pylint/extensions/_check_docs_utils.py
index 59f5dd992..70b312539 100644
--- a/pylint/extensions/_check_docs_utils.py
+++ b/pylint/extensions/_check_docs_utils.py
@@ -34,7 +34,7 @@ from pylint.checkers import utils
def space_indentation(s):
- """The number of leading spaces in a string
+ """The number of leading spaces in a string.
:param str s: input string
@@ -216,7 +216,7 @@ class Docstring:
return f"<{self.__class__.__name__}:'''{self.doc}'''>"
def matching_sections(self) -> int:
- """Returns the number of matching docstring sections"""
+ """Returns the number of matching docstring sections."""
return 0
def exceptions(self):
@@ -329,7 +329,7 @@ class SphinxDocstring(Docstring):
supports_yields = False
def matching_sections(self) -> int:
- """Returns the number of matching docstring sections"""
+ """Returns the number of matching docstring sections."""
return sum(
bool(i)
for i in (
@@ -536,7 +536,7 @@ class GoogleDocstring(Docstring):
supports_yields = True
def matching_sections(self) -> int:
- """Returns the number of matching docstring sections"""
+ """Returns the number of matching docstring sections."""
return sum(
bool(i)
for i in (
@@ -782,7 +782,7 @@ class NumpyDocstring(GoogleDocstring):
supports_yields = True
def match_param_docs(self) -> Tuple[Set[str], Set[str]]:
- """Matches parameter documentation section to parameter documentation rules"""
+ """Matches parameter documentation section to parameter documentation rules."""
params_with_doc = set()
params_with_type = set()
diff --git a/pylint/extensions/check_elif.py b/pylint/extensions/check_elif.py
index 1fb6323b2..0563d5170 100644
--- a/pylint/extensions/check_elif.py
+++ b/pylint/extensions/check_elif.py
@@ -25,7 +25,7 @@ if TYPE_CHECKING:
class ElseifUsedChecker(BaseTokenChecker):
- """Checks for use of "else if" when an "elif" could be used"""
+ """Checks for use of "else if" when an "elif" could be used."""
__implements__ = (ITokenChecker, IAstroidChecker)
name = "else_if_used"
@@ -47,7 +47,7 @@ class ElseifUsedChecker(BaseTokenChecker):
self._elifs = {}
def process_tokens(self, tokens):
- """Process tokens and look for 'if' or 'elif'"""
+ """Process tokens and look for 'if' or 'elif'."""
self._elifs = {
begin: token for _, token, begin, _, _ in tokens if token in {"elif", "if"}
}
@@ -57,7 +57,7 @@ class ElseifUsedChecker(BaseTokenChecker):
@check_messages("else-if-used")
def visit_if(self, node: nodes.If) -> None:
- """Current if node must directly follow an 'else'"""
+ """Current if node must directly follow an 'else'."""
if (
isinstance(node.parent, nodes.If)
and node.parent.orelse == [node]
diff --git a/pylint/extensions/comparison_placement.py b/pylint/extensions/comparison_placement.py
index e045ebdd0..f34f1eb82 100644
--- a/pylint/extensions/comparison_placement.py
+++ b/pylint/extensions/comparison_placement.py
@@ -21,7 +21,7 @@ COMPARISON_OPERATORS = frozenset(("==", "!=", "<", ">", "<=", ">="))
class MisplacedComparisonConstantChecker(BaseChecker):
- """Checks the placement of constants in comparisons"""
+ """Checks the placement of constants in comparisons."""
__implements__ = (IAstroidChecker,)
diff --git a/pylint/extensions/docparams.py b/pylint/extensions/docparams.py
index 7c18e6b62..35324ac04 100644
--- a/pylint/extensions/docparams.py
+++ b/pylint/extensions/docparams.py
@@ -24,7 +24,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
-"""Pylint plugin for checking in Sphinx, Google, or Numpy style docstrings"""
+"""Pylint plugin for checking in Sphinx, Google, or Numpy style docstrings."""
import re
from typing import TYPE_CHECKING, Optional
@@ -43,7 +43,7 @@ if TYPE_CHECKING:
class DocstringParameterChecker(BaseChecker):
- """Checker for Sphinx, Google, or Numpy style docstrings
+ """Checker for Sphinx, Google, or Numpy style docstrings.
* Check that all function, method and constructor parameters are mentioned
in the params and types part of the docstring. Constructor parameters
diff --git a/pylint/extensions/docstyle.py b/pylint/extensions/docstyle.py
index d2f07003b..7dc26db5d 100644
--- a/pylint/extensions/docstyle.py
+++ b/pylint/extensions/docstyle.py
@@ -25,7 +25,7 @@ if TYPE_CHECKING:
class DocStringStyleChecker(checkers.BaseChecker):
- """Checks format of docstrings based on PEP 0257"""
+ """Checks format of docstrings based on PEP 0257."""
__implements__ = IAstroidChecker
name = "docstyle"
diff --git a/pylint/extensions/empty_comment.py b/pylint/extensions/empty_comment.py
index c52540308..68b48970d 100644
--- a/pylint/extensions/empty_comment.py
+++ b/pylint/extensions/empty_comment.py
@@ -10,7 +10,7 @@ if TYPE_CHECKING:
def is_line_commented(line):
- """Checks if a `# symbol that is not part of a string was found in line"""
+ """Checks if a `# symbol that is not part of a string was found in line."""
comment_idx = line.find(b"#")
if comment_idx == -1:
@@ -21,7 +21,7 @@ def is_line_commented(line):
def comment_part_of_string(line, comment_idx):
- """checks if the symbol at comment_idx is part of a string"""
+ """Checks if the symbol at comment_idx is part of a string."""
if (
line[:comment_idx].count(b"'") % 2 == 1
diff --git a/pylint/extensions/mccabe.py b/pylint/extensions/mccabe.py
index d675087fe..b84865dec 100644
--- a/pylint/extensions/mccabe.py
+++ b/pylint/extensions/mccabe.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
-"""Module to add McCabe checker class for pylint. """
+"""Module to add McCabe checker class for pylint."""
from typing import TYPE_CHECKING
@@ -115,7 +115,7 @@ class PathGraphingAstVisitor(Mccabe_PathGraphingAstVisitor):
return node
def _subgraph(self, node, name, extra_blocks=()):
- """create the subgraphs representing any `if` and `for` statements"""
+ """Create the subgraphs representing any `if` and `for` statements."""
if self.graph is None:
# global loop
self.graph = PathGraph(node)
@@ -127,7 +127,7 @@ class PathGraphingAstVisitor(Mccabe_PathGraphingAstVisitor):
self._subgraph_parse(node, node, extra_blocks)
def _subgraph_parse(self, node, pathnode, extra_blocks):
- """parse the body and any `else` block of `if` and `for` statements"""
+ """Parse the body and any `else` block of `if` and `for` statements."""
loose_ends = []
self.tail = node
self.dispatch_list(node.body)
@@ -180,7 +180,7 @@ class McCabeMethodChecker(checkers.BaseChecker):
@check_messages("too-complex")
def visit_module(self, node: nodes.Module) -> None:
- """visit an astroid.Module node to check too complex rating and
+ """Visit an astroid.Module node to check too complex rating and
add message if is greater than max_complexity stored from options
"""
visitor = PathGraphingAstVisitor()
diff --git a/pylint/extensions/overlapping_exceptions.py b/pylint/extensions/overlapping_exceptions.py
index 9729fd112..11c79eb04 100644
--- a/pylint/extensions/overlapping_exceptions.py
+++ b/pylint/extensions/overlapping_exceptions.py
@@ -37,7 +37,7 @@ class OverlappingExceptionsChecker(checkers.BaseChecker):
@utils.check_messages("overlapping-except")
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
- """check for empty except"""
+ """Check for empty except."""
for handler in node.handlers:
if handler.type is None:
continue
diff --git a/pylint/extensions/redefined_variable_type.py b/pylint/extensions/redefined_variable_type.py
index 775f7adae..527418bf5 100644
--- a/pylint/extensions/redefined_variable_type.py
+++ b/pylint/extensions/redefined_variable_type.py
@@ -24,7 +24,7 @@ if TYPE_CHECKING:
class MultipleTypesChecker(BaseChecker):
- """Checks for variable type redefinitions (NoneType excepted)
+ """Checks for variable type redefinitions (NoneType excepted).
At a function, method, class or module scope
diff --git a/pylint/graph.py b/pylint/graph.py
index 70a618678..f75ce4e64 100644
--- a/pylint/graph.py
+++ b/pylint/graph.py
@@ -74,7 +74,7 @@ class DotBackend:
self.emit("=".join(param))
def get_source(self):
- """returns self._source"""
+ """Returns self._source."""
if self._source is None:
self.emit("}\n")
self._source = "\n".join(self.lines)
@@ -151,7 +151,7 @@ class DotBackend:
self.lines.append(line)
def emit_edge(self, name1, name2, **props):
- """emit an edge from <name1> to <name2>.
+ """Emit an edge from <name1> to <name2>.
edge properties: see https://www.graphviz.org/doc/info/attrs.html
"""
attrs = [f'{prop}="{value}"' for prop, value in props.items()]
@@ -159,7 +159,7 @@ class DotBackend:
self.emit(f"{n_from} -> {n_to} [{', '.join(sorted(attrs))}];")
def emit_node(self, name, **props):
- """emit a node with given properties.
+ """Emit a node with given properties.
node properties: see https://www.graphviz.org/doc/info/attrs.html
"""
attrs = [f'{prop}="{value}"' for prop, value in props.items()]
@@ -172,7 +172,7 @@ def normalize_node_id(nid):
def get_cycles(graph_dict, vertices=None):
- """given a dictionary representing an ordered graph (i.e. key are vertices
+ """Given a dictionary representing an ordered graph (i.e. key are vertices
and values is a list of destination vertices representing edges), return a
list of detected cycles
"""
@@ -187,7 +187,7 @@ def get_cycles(graph_dict, vertices=None):
def _get_cycles(graph_dict, path, visited, result, vertice):
- """recursive function doing the real work for get_cycles"""
+ """Recursive function doing the real work for get_cycles."""
if vertice in path:
cycle = [vertice]
for node in path[::-1]:
diff --git a/pylint/interfaces.py b/pylint/interfaces.py
index 103eb207b..e2b4b4422 100644
--- a/pylint/interfaces.py
+++ b/pylint/interfaces.py
@@ -17,7 +17,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
-"""Interfaces for Pylint objects"""
+"""Interfaces for Pylint objects."""
from collections import namedtuple
from typing import TYPE_CHECKING, Tuple, Type, Union
@@ -79,17 +79,17 @@ class IChecker(Interface):
"""Base interface, to be used only for sub interfaces definition."""
def open(self):
- """called before visiting project (i.e. set of modules)"""
+ """Called before visiting project (i.e. set of modules)."""
def close(self):
- """called after visiting project (i.e. set of modules)"""
+ """Called after visiting project (i.e. set of modules)."""
class IRawChecker(IChecker):
- """Interface for checker which need to parse the raw file"""
+ """Interface for checker which need to parse the raw file."""
def process_module(self, node: nodes.Module) -> None:
- """process a module
+ """Process a module.
The module's content is accessible via ``astroid.stream``
"""
@@ -106,16 +106,16 @@ class ITokenChecker(IChecker):
class IAstroidChecker(IChecker):
- """interface for checker which prefers receive events according to
+ """Interface for checker which prefers receive events according to
statement type
"""
class IReporter(Interface):
- """reporter collect messages and display results encapsulated in a layout"""
+ """Reporter collect messages and display results encapsulated in a layout."""
def handle_message(self, msg) -> None:
"""Handle the given message object."""
def display_reports(self, layout: "Section") -> None:
- """display results encapsulated in the layout tree"""
+ """Display results encapsulated in the layout tree."""
diff --git a/pylint/lint/__init__.py b/pylint/lint/__init__.py
index 69d0f95d1..ae3c56c89 100644
--- a/pylint/lint/__init__.py
+++ b/pylint/lint/__init__.py
@@ -59,7 +59,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
-""" pylint [options] modules_or_packages
+"""Pylint [options] modules_or_packages.
Check that module(s) satisfy a coding standard (and more !).
diff --git a/pylint/lint/expand_modules.py b/pylint/lint/expand_modules.py
index 4d3600a00..296e6b577 100644
--- a/pylint/lint/expand_modules.py
+++ b/pylint/lint/expand_modules.py
@@ -33,7 +33,7 @@ def get_python_path(filepath: str) -> str:
def _is_in_ignore_list_re(element: str, ignore_list_re: List[Pattern]) -> bool:
- """determines if the element is matched in a regex ignore-list"""
+ """Determines if the element is matched in a regex ignore-list."""
return any(file_pattern.match(element) for file_pattern in ignore_list_re)
@@ -43,7 +43,7 @@ def expand_modules(
ignore_list_re: List[Pattern],
ignore_list_paths_re: List[Pattern[str]],
) -> Tuple[List[ModuleDescriptionDict], List[ErrorDescriptionDict]]:
- """take a list of files/modules/packages and return the list of tuple
+ """Take a list of files/modules/packages and return the list of tuple
(file, module name) which have to be actually checked
"""
result: List[ModuleDescriptionDict] = []
diff --git a/pylint/lint/parallel.py b/pylint/lint/parallel.py
index 63b1e812b..f3e2d6cb4 100644
--- a/pylint/lint/parallel.py
+++ b/pylint/lint/parallel.py
@@ -51,7 +51,7 @@ def _get_new_args(message):
def _worker_initialize(
linter: bytes, arguments: Union[None, str, Sequence[str]] = None
) -> None:
- """Function called to initialize a worker for a Process within a multiprocessing Pool
+ """Function called to initialize a worker for a Process within a multiprocessing Pool.
:param linter: A linter-class (PyLinter) instance pickled with dill
:param arguments: File or module name(s) to lint and to be added to sys.path
@@ -107,7 +107,7 @@ def _worker_check_single_file(
def _merge_mapreduce_data(linter, all_mapreduce_data):
- """Merges map/reduce data across workers, invoking relevant APIs on checkers"""
+ """Merges map/reduce data across workers, invoking relevant APIs on checkers."""
# First collate the data and prepare it, so we can send it to the checkers for
# validation. The intent here is to collect all the mapreduce data for all checker-
# runs across processes - that will then be passed to a static method on the
diff --git a/pylint/lint/pylinter.py b/pylint/lint/pylinter.py
index 36651c04d..2f5389d61 100644
--- a/pylint/lint/pylinter.py
+++ b/pylint/lint/pylinter.py
@@ -193,7 +193,7 @@ class PyLinter(
reporters.ReportsHandlerMixIn,
checkers.BaseTokenChecker,
):
- """lint Python modules using external checkers.
+ """Lint Python modules using external checkers.
This is the main checker controlling the other ones and the reports
generation. It is itself both a raw checker and an astroid checker in order
@@ -560,15 +560,15 @@ class PyLinter(
else:
self.set_reporter(TextReporter())
self._reporters: Dict[str, Type[reporters.BaseReporter]] = {}
- """Dictionary of possible but non-initialized reporters"""
+ """Dictionary of possible but non-initialized reporters."""
# Attributes for checkers and plugins
self._checkers: DefaultDict[
str, List[checkers.BaseChecker]
] = collections.defaultdict(list)
- """Dictionary of registered and initialized checkers"""
+ """Dictionary of registered and initialized checkers."""
self._dynamic_plugins: Set[str] = set()
- """Set of loaded plugin names"""
+ """Set of loaded plugin names."""
# Attributes related to visiting files
self.file_state = FileState()
@@ -598,7 +598,7 @@ class PyLinter(
"enable-msg": self._options_methods["enable"],
}
self.fail_on_symbols: List[str] = []
- """List of message symbols on which pylint should fail, set by --fail-on"""
+ """List of message symbols on which pylint should fail, set by --fail-on."""
self._error_mode = False
# Attributes related to messages (states) and their handling
@@ -631,7 +631,7 @@ class PyLinter(
reporters.initialize(self)
def load_plugin_modules(self, modnames):
- """take a list of module names which are pylint plugins and load
+ """Take a list of module names which are pylint plugins and load
and register them
"""
for modname in modnames:
@@ -645,7 +645,7 @@ class PyLinter(
pass
def load_plugin_configuration(self):
- """Call the configuration hook for plugins
+ """Call the configuration hook for plugins.
This walks through the list of plugins, grabs the "load_configuration"
hook, if exposed, and calls it to allow plugins to configure specific
@@ -660,7 +660,7 @@ class PyLinter(
self.add_message("bad-plugin-value", args=(modname, e), line=0)
def _load_reporters(self, reporter_names: str) -> None:
- """Load the reporters if they are available on _reporters"""
+ """Load the reporters if they are available on _reporters."""
if not self._reporters:
return
sub_reporters = []
@@ -706,12 +706,12 @@ class PyLinter(
def set_reporter(
self, reporter: Union[reporters.BaseReporter, reporters.MultiReporter]
) -> None:
- """set the reporter used to display messages and reports"""
+ """Set the reporter used to display messages and reports."""
self.reporter = reporter
reporter.linter = self
def set_option(self, optname, value, action=None, optdict=None):
- """overridden from config.OptionsProviderMixin to handle some
+ """Overridden from config.OptionsProviderMixin to handle some
special options
"""
if optname in self._options_methods or optname in self._bw_options_methods:
@@ -774,7 +774,7 @@ class PyLinter(
self.disable(checker.name)
def enable_fail_on_messages(self):
- """enable 'fail on' msgs
+ """Enable 'fail on' msgs.
Convert values in config.fail_on (which might be msg category, msg id,
or symbol) to specific msgs, then enable and flag them for later.
@@ -820,13 +820,13 @@ class PyLinter(
self.disable(msgid)
def disable_reporters(self):
- """disable all reporters"""
+ """Disable all reporters."""
for _reporters in self._reports.values():
for report_id, _, _ in _reporters:
self.disable_report(report_id)
def error_mode(self):
- """error mode: enable only errors; no reports, no persistent"""
+ """Error mode: enable only errors; no reports, no persistent."""
self._error_mode = True
self.disable_noerror_messages()
self.disable("miscellaneous")
@@ -941,7 +941,7 @@ class PyLinter(
# code checking methods ###################################################
def get_checkers(self):
- """return all available checkers as a list"""
+ """Return all available checkers as a list."""
return [self] + [
c
for _checkers in self._checkers.values()
@@ -961,7 +961,7 @@ class PyLinter(
)
def prepare_checkers(self):
- """return checkers needed for activated messages and reports"""
+ """Return checkers needed for activated messages and reports."""
if not self.config.reports:
self.disable_reporters()
# get needed checkers
@@ -1002,7 +1002,7 @@ class PyLinter(
# pylint: enable=unused-argument
def initialize(self):
- """Initialize linter for linting
+ """Initialize linter for linting.
This method is called before any linting is done.
"""
@@ -1040,7 +1040,7 @@ class PyLinter(
yield something
def check(self, files_or_modules: Union[Sequence[str], str]) -> None:
- """main checking entry: check a list of files or modules from their name.
+ """Main checking entry: check a list of files or modules from their name.
files_or_modules is either a string or list of strings presenting modules to check.
"""
@@ -1089,7 +1089,7 @@ class PyLinter(
self.check_single_file_item(FileItem(name, filepath, modname))
def check_single_file_item(self, file: FileItem) -> None:
- """Check single file item
+ """Check single file item.
The arguments are the same that are documented in _check_files
@@ -1103,7 +1103,7 @@ class PyLinter(
get_ast,
file_descrs: Iterable[FileItem],
) -> None:
- """Check all files from file_descrs"""
+ """Check all files from file_descrs."""
with self._astroid_module_checker() as check_astroid_module:
for file in file_descrs:
try:
@@ -1121,7 +1121,7 @@ class PyLinter(
self.add_message(symbol, args=msg)
def _check_file(self, get_ast, check_astroid_module, file: FileItem):
- """Check a file using the passed utility functions (get_ast and check_astroid_module)
+ """Check a file using the passed utility functions (get_ast and check_astroid_module).
:param callable get_ast: callable returning AST from defined file taking the following arguments
- filepath: path to the file to check
@@ -1152,7 +1152,7 @@ class PyLinter(
@staticmethod
def _get_file_descr_from_stdin(filepath: str) -> FileItem:
- """Return file description (tuple of module name, file path, base name) from given file path
+ """Return file description (tuple of module name, file path, base name) from given file path.
This method is used for creating suitable file description for _check_files when the
source is standard input.
@@ -1168,7 +1168,7 @@ class PyLinter(
return FileItem(modname, filepath, filepath)
def _iterate_file_descrs(self, files_or_modules) -> Iterator[FileItem]:
- """Return generator yielding file descriptions (tuples of module name, file path, base name)
+ """Return generator yielding file descriptions (tuples of module name, file path, base name).
The returned generator yield one item for each Python module that should be linted.
"""
@@ -1178,7 +1178,7 @@ class PyLinter(
yield FileItem(name, filepath, descr["basename"])
def _expand_files(self, modules) -> List[ModuleDescriptionDict]:
- """get modules and errors from a list of modules and handle errors"""
+ """Get modules and errors from a list of modules and handle errors."""
result, errors = expand_modules(
modules,
self.config.black_list,
@@ -1195,7 +1195,7 @@ class PyLinter(
return result
def set_current_module(self, modname, filepath: Optional[str] = None):
- """set the name of the currently analyzed module and
+ """Set the name of the currently analyzed module and
init statistics for it
"""
if not modname and filepath is None:
@@ -1216,7 +1216,7 @@ class PyLinter(
@contextlib.contextmanager
def _astroid_module_checker(self):
- """Context manager for checking ASTs
+ """Context manager for checking ASTs.
The value in the context is callable accepting AST as its only argument.
"""
@@ -1307,7 +1307,7 @@ class PyLinter(
def _check_astroid_module(
self, node: nodes.Module, walker, rawcheckers, tokencheckers
):
- """Check given AST node with given walker and checkers
+ """Check given AST node with given walker and checkers.
:param astroid.nodes.Module node: AST node of the module to check
:param pylint.utils.ast_walker.ASTWalker walker: AST walker
@@ -1347,7 +1347,7 @@ class PyLinter(
# IAstroidChecker interface #################################################
def open(self):
- """initialize counters"""
+ """Initialize counters."""
self.stats = LinterStats()
MANAGER.always_load_extensions = self.config.unsafe_load_any_extension
MANAGER.max_inferable_values = self.config.limit_inference_results
@@ -1360,7 +1360,7 @@ class PyLinter(
self._ignore_paths = get_global_option(self, "ignore-paths")
def generate_reports(self):
- """close the whole package /module, it's time to make reports !
+ """Close the whole package /module, it's time to make reports !
if persistent run, pickle results for later comparison
"""
@@ -1388,7 +1388,7 @@ class PyLinter(
return score_value
def _report_evaluation(self):
- """make the global evaluation report"""
+ """Make the global evaluation report."""
# check with at least check 1 statements (usually 0 when there is a
# syntax error preventing pylint from further processing)
note = None
@@ -1445,7 +1445,7 @@ class PyLinter(
return None
def _is_one_message_enabled(self, msgid: str, line: Optional[int]) -> bool:
- """Checks state of a single message for the current file
+ """Checks state of a single message for the current file.
This function can't be cached as it depends on self.file_state which can
change.
@@ -1635,7 +1635,7 @@ class PyLinter(
node: Optional[nodes.NodeNG] = None,
confidence: Optional[interfaces.Confidence] = interfaces.UNDEFINED,
) -> None:
- """Prepares a message to be added to the ignored message storage
+ """Prepares a message to be added to the ignored message storage.
Some checks return early in special cases and never reach add_message(),
even though they would normally issue a message.
@@ -1656,7 +1656,7 @@ class PyLinter(
# Setting the state (disabled/enabled) of messages and registering them
def _message_symbol(self, msgid: str) -> List[str]:
- """Get the message symbol of the given message id
+ """Get the message symbol of the given message id.
Return the original message id if the message does not
exist.
@@ -1669,7 +1669,7 @@ class PyLinter(
def _set_one_msg_status(
self, scope: str, msg: MessageDefinition, line: Optional[int], enable: bool
) -> None:
- """Set the status of an individual message"""
+ """Set the status of an individual message."""
if scope == "module":
assert isinstance(line, int) # should always be int inside module scope
@@ -1740,7 +1740,7 @@ class PyLinter(
line: Optional[int] = None,
ignore_unknown: bool = False,
) -> None:
- """Do some tests and then iterate over message definitions to set state"""
+ """Do some tests and then iterate over message definitions to set state."""
assert scope in {"package", "module"}
message_definitions = self._get_messages_to_set(msgid, enable, ignore_unknown)
@@ -1782,7 +1782,7 @@ class PyLinter(
line: Optional[int] = None,
ignore_unknown: bool = False,
) -> None:
- """Disable a message for a scope"""
+ """Disable a message for a scope."""
self._set_msg_status(
msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown
)
@@ -1795,7 +1795,7 @@ class PyLinter(
line: Optional[int] = None,
ignore_unknown: bool = False,
) -> None:
- """Disable a message for the next line"""
+ """Disable a message for the next line."""
if not line:
raise exceptions.NoLineSuppliedError
self._set_msg_status(
@@ -1814,7 +1814,7 @@ class PyLinter(
line: Optional[int] = None,
ignore_unknown: bool = False,
) -> None:
- """Enable a message for a scope"""
+ """Enable a message for a scope."""
self._set_msg_status(
msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown
)
diff --git a/pylint/lint/report_functions.py b/pylint/lint/report_functions.py
index 5e95354c4..0f5e9360d 100644
--- a/pylint/lint/report_functions.py
+++ b/pylint/lint/report_functions.py
@@ -14,7 +14,7 @@ def report_total_messages_stats(
stats: LinterStats,
previous_stats: LinterStats,
):
- """make total errors / warnings report"""
+ """Make total errors / warnings report."""
lines = ["type", "number", "previous", "difference"]
lines += checkers.table_lines_from_stats(stats, previous_stats, "message_types")
sect.append(Table(children=lines, cols=4, rheaders=1))
@@ -25,7 +25,7 @@ def report_messages_stats(
stats: LinterStats,
_: LinterStats,
):
- """make messages type report"""
+ """Make messages type report."""
by_msg_stats = stats.by_msg
in_order = sorted(
(value, msg_id)
@@ -44,7 +44,7 @@ def report_messages_by_module_stats(
stats: LinterStats,
_: LinterStats,
):
- """make errors / warnings by modules report"""
+ """Make errors / warnings by modules report."""
module_stats = stats.by_module
if len(module_stats) == 1:
# don't print this report when we are analysing a single module
diff --git a/pylint/lint/run.py b/pylint/lint/run.py
index 0adba0723..25311024a 100644
--- a/pylint/lint/run.py
+++ b/pylint/lint/run.py
@@ -31,7 +31,7 @@ def _cpu_count() -> int:
def cb_list_extensions(option, optname, value, parser):
- """List all the extensions under pylint.extensions"""
+ """List all the extensions under pylint.extensions."""
for filename in os.listdir(os.path.dirname(extensions.__file__)):
if filename.endswith(".py") and not filename.startswith("_"):
@@ -47,7 +47,7 @@ def cb_list_confidence_levels(option, optname, value, parser):
def cb_init_hook(optname, value):
- """Execute arbitrary code to set 'sys.path' for instance"""
+ """Execute arbitrary code to set 'sys.path' for instance."""
exec(value) # pylint: disable=exec-used
@@ -55,7 +55,7 @@ UNUSED_PARAM_SENTINEL = object()
class Run:
- """helper class to use as main for pylint :
+ """Helper class to use as main for pylint :.
run(*sys.argv[1:])
"""
@@ -385,23 +385,23 @@ to search for configuration file.
sys.exit(self.linter.msg_status)
def version_asked(self, _, __):
- """callback for version (i.e. before option parsing)"""
+ """Callback for version (i.e. before option parsing)."""
self._version_asked = True
def cb_set_rcfile(self, name, value):
- """callback for option preprocessing (i.e. before option parsing)"""
+ """Callback for option preprocessing (i.e. before option parsing)."""
self._rcfile = value
def cb_set_output(self, name, value):
- """callback for option preprocessing (i.e. before option parsing)"""
+ """Callback for option preprocessing (i.e. before option parsing)."""
self._output = value
def cb_add_plugins(self, name, value):
- """callback for option preprocessing (i.e. before option parsing)"""
+ """Callback for option preprocessing (i.e. before option parsing)."""
self._plugins.extend(utils._splitstrip(value))
def cb_error_mode(self, *args, **kwargs):
- """error mode:
+ """Error mode:
* disable all but error messages
* disable the 'miscellaneous' checker which can be safely deactivated in
debug
@@ -411,37 +411,37 @@ to search for configuration file.
self.linter.error_mode()
def cb_generate_config(self, *args, **kwargs):
- """optik callback for sample config file generation"""
+ """Optik callback for sample config file generation."""
self.linter.generate_config(skipsections=("COMMANDS",))
sys.exit(0)
def cb_generate_manpage(self, *args, **kwargs):
- """optik callback for sample config file generation"""
+ """Optik callback for sample config file generation."""
self.linter.generate_manpage(__pkginfo__)
sys.exit(0)
def cb_help_message(self, option, optname, value, parser):
- """optik callback for printing some help about a particular message"""
+ """Optik callback for printing some help about a particular message."""
self.linter.msgs_store.help_message(utils._splitstrip(value))
sys.exit(0)
def cb_full_documentation(self, option, optname, value, parser):
- """optik callback for printing full documentation"""
+ """Optik callback for printing full documentation."""
print_full_documentation(self.linter)
sys.exit(0)
def cb_list_messages(self, option, optname, value, parser):
- """optik callback for printing available messages"""
+ """Optik callback for printing available messages."""
self.linter.msgs_store.list_messages()
sys.exit(0)
def cb_list_messages_enabled(self, option, optname, value, parser):
- """optik callback for printing available messages"""
+ """Optik callback for printing available messages."""
self.linter.list_messages_enabled()
sys.exit(0)
def cb_list_groups(self, *args, **kwargs):
- """List all the check groups that pylint knows about
+ """List all the check groups that pylint knows about.
These should be useful to know what check groups someone can disable
or enable.
@@ -454,7 +454,7 @@ to search for configuration file.
self.verbose = True
def cb_enable_all_extensions(self, option_name: str, value: None) -> None:
- """Callback to load and enable all available extensions"""
+ """Callback to load and enable all available extensions."""
for filename in os.listdir(os.path.dirname(extensions.__file__)):
if filename.endswith(".py") and not filename.startswith("_"):
extension_name = f"pylint.extensions.{filename[:-3]}"
diff --git a/pylint/lint/utils.py b/pylint/lint/utils.py
index fb1093d80..410269e9d 100644
--- a/pylint/lint/utils.py
+++ b/pylint/lint/utils.py
@@ -69,7 +69,7 @@ def get_fatal_error_message(filepath: str, issue_template_path: Path) -> str:
def preprocess_options(args, search_for):
- """look for some options (keys of <search_for>) which have to be processed
+ """Look for some options (keys of <search_for>) which have to be processed
before others
values of <search_for> are callback functions to call when the option is
diff --git a/pylint/message/message.py b/pylint/message/message.py
index b431d502b..8a12d84b8 100644
--- a/pylint/message/message.py
+++ b/pylint/message/message.py
@@ -32,7 +32,7 @@ _MsgBase = collections.namedtuple(
class Message(_MsgBase):
- """This class represent a message to be issued by the reporters"""
+ """This class represent a message to be issued by the reporters."""
@overload
def __new__(
diff --git a/pylint/message/message_definition.py b/pylint/message/message_definition.py
index 8785e154d..a286f5a6d 100644
--- a/pylint/message/message_definition.py
+++ b/pylint/message/message_definition.py
@@ -58,7 +58,7 @@ class MessageDefinition:
return f"{repr(self)}:\n{self.msg} {self.description}"
def may_be_emitted(self) -> bool:
- """return True if message may be emitted using the current interpreter"""
+ """Return True if message may be emitted using the current interpreter."""
if self.minversion is not None and self.minversion > sys.version_info:
return False
if self.maxversion is not None and self.maxversion <= sys.version_info:
@@ -66,7 +66,7 @@ class MessageDefinition:
return True
def format_help(self, checkerref: bool = False) -> str:
- """return the help string for the given message id"""
+ """Return the help string for the given message id."""
desc = self.description
if checkerref:
desc += f" This message belongs to the {self.checker_name} checker."
@@ -94,7 +94,7 @@ class MessageDefinition:
def check_message_definition(
self, line: Optional[int], node: Optional[nodes.NodeNG]
) -> None:
- """Check MessageDefinition for possible errors"""
+ """Check MessageDefinition for possible errors."""
if self.msgid[0] not in _SCOPE_EXEMPT:
# Fatal messages and reports are special, the node/scope distinction
# does not apply to them.
diff --git a/pylint/message/message_definition_store.py b/pylint/message/message_definition_store.py
index 150c35fe8..c8b4e166a 100644
--- a/pylint/message/message_definition_store.py
+++ b/pylint/message/message_definition_store.py
@@ -72,7 +72,7 @@ class MessageDefinitionStore:
return repr([md.symbol for md in message_definitions])
def help_message(self, msgids_or_symbols: List[str]) -> None:
- """Display help messages for the given message identifiers"""
+ """Display help messages for the given message identifiers."""
for msgids_or_symbol in msgids_or_symbols:
try:
for message_definition in self.get_message_definitions(
@@ -99,7 +99,7 @@ class MessageDefinitionStore:
def find_emittable_messages(
self,
) -> Tuple[List[MessageDefinition], List[MessageDefinition]]:
- """Finds all emittable and non-emittable messages"""
+ """Finds all emittable and non-emittable messages."""
messages = sorted(self._messages_definitions.values(), key=lambda m: m.msgid)
emittable = []
non_emittable = []
diff --git a/pylint/pyreverse/__init__.py b/pylint/pyreverse/__init__.py
index 390244522..cce5caec3 100644
--- a/pylint/pyreverse/__init__.py
+++ b/pylint/pyreverse/__init__.py
@@ -1,6 +1,6 @@
# 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
-"""pyreverse.extensions"""
+"""Pyreverse.extensions."""
__revision__ = "$Id $"
diff --git a/pylint/pyreverse/diadefslib.py b/pylint/pyreverse/diadefslib.py
index 1e059dea3..44a593849 100644
--- a/pylint/pyreverse/diadefslib.py
+++ b/pylint/pyreverse/diadefslib.py
@@ -19,7 +19,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
-"""handle diagram generation options for class diagram or default diagrams"""
+"""Handle diagram generation options for class diagram or default diagrams."""
from typing import Any, Optional
@@ -34,24 +34,24 @@ from pylint.pyreverse.utils import LocalsVisitor
class DiaDefGenerator:
- """handle diagram generation options"""
+ """Handle diagram generation options."""
def __init__(self, linker, handler):
- """common Diagram Handler initialization"""
+ """Common Diagram Handler initialization."""
self.config = handler.config
self._set_default_options()
self.linker = linker
self.classdiagram = None # defined by subclasses
def get_title(self, node):
- """get title for objects"""
+ """Get title for objects."""
title = node.name
if self.module_names:
title = f"{node.root().name}.{title}"
return title
def _set_option(self, option):
- """activate some options if not explicitly deactivated"""
+ """Activate some options if not explicitly deactivated."""
# if we have a class diagram, we want more information by default;
# so if the option is None, we return True
if option is None:
@@ -59,7 +59,7 @@ class DiaDefGenerator:
return option
def _set_default_options(self):
- """set different default options with _default dictionary"""
+ """Set different default options with _default dictionary."""
self.module_names = self._set_option(self.config.module_names)
all_ancestors = self._set_option(self.config.all_ancestors)
all_associated = self._set_option(self.config.all_associated)
@@ -75,22 +75,22 @@ class DiaDefGenerator:
self.anc_level, self.association_level = anc_level, association_level
def _get_levels(self):
- """help function for search levels"""
+ """Help function for search levels."""
return self.anc_level, self.association_level
def show_node(self, node):
- """true if builtins and not show_builtins"""
+ """True if builtins and not show_builtins."""
if self.config.show_builtin:
return True
return node.root().name != "builtins"
def add_class(self, node):
- """visit one class and add it to diagram"""
+ """Visit one class and add it to diagram."""
self.linker.visit(node)
self.classdiagram.add_object(self.get_title(node), node)
def get_ancestors(self, node, level):
- """return ancestor nodes of a class node"""
+ """Return ancestor nodes of a class node."""
if level == 0:
return
for ancestor in node.ancestors(recurs=False):
@@ -99,7 +99,7 @@ class DiaDefGenerator:
yield ancestor
def get_associated(self, klass_node, level):
- """return associated nodes of a class node"""
+ """Return associated nodes of a class node."""
if level == 0:
return
for association_nodes in list(klass_node.instance_attrs_type.values()) + list(
@@ -113,7 +113,7 @@ class DiaDefGenerator:
yield node
def extract_classes(self, klass_node, anc_level, association_level):
- """extract recursively classes related to klass_node"""
+ """Extract recursively classes related to klass_node."""
if self.classdiagram.has_node(klass_node) or not self.show_node(klass_node):
return
self.add_class(klass_node)
@@ -126,7 +126,7 @@ class DiaDefGenerator:
class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator):
- """generate minimum diagram definition for the project :
+ """Generate minimum diagram definition for the project :.
* a package diagram including project's modules
* a class diagram including project's classes
@@ -137,7 +137,7 @@ class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator):
LocalsVisitor.__init__(self)
def visit_project(self, node: Project) -> None:
- """visit a pyreverse.utils.Project node
+ """Visit a pyreverse.utils.Project node.
create a diagram definition for packages
"""
@@ -151,7 +151,7 @@ class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator):
self.classdiagram = ClassDiagram(f"classes {node.name}", mode)
def leave_project(self, _: Project) -> Any:
- """leave the pyreverse.utils.Project node
+ """Leave the pyreverse.utils.Project node.
return the generated diagram definition
"""
@@ -160,7 +160,7 @@ class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator):
return (self.classdiagram,)
def visit_module(self, node: nodes.Module) -> None:
- """visit an astroid.Module node
+ """Visit an astroid.Module node.
add this class to the package diagram definition
"""
@@ -169,7 +169,7 @@ class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator):
self.pkgdiagram.add_object(node.name, node)
def visit_classdef(self, node: nodes.ClassDef) -> None:
- """visit an astroid.Class node
+ """Visit an astroid.Class node.
add this class to the class diagram definition
"""
@@ -177,18 +177,18 @@ class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator):
self.extract_classes(node, anc_level, association_level)
def visit_importfrom(self, node: nodes.ImportFrom) -> None:
- """visit astroid.ImportFrom and catch modules for package diagram"""
+ """Visit astroid.ImportFrom and catch modules for package diagram."""
if self.pkgdiagram:
self.pkgdiagram.add_from_depend(node, node.modname)
class ClassDiadefGenerator(DiaDefGenerator):
- """generate a class diagram definition including all classes related to a
+ """Generate a class diagram definition including all classes related to a
given class
"""
def class_diagram(self, project, klass):
- """return a class diagram definition for the given klass and its
+ """Return a class diagram definition for the given klass and its
related klasses
"""
@@ -210,7 +210,7 @@ class ClassDiadefGenerator(DiaDefGenerator):
class DiadefsHandler:
- """handle diagram definitions :
+ """Handle diagram definitions :.
get it from user (i.e. xml files) or generate them
"""
@@ -219,7 +219,7 @@ class DiadefsHandler:
self.config = config
def get_diadefs(self, project, linker):
- """Get the diagram's configuration data
+ """Get the diagram's configuration data.
:param project:The pyreverse project
:type project: pyreverse.utils.Project
diff --git a/pylint/pyreverse/diagrams.py b/pylint/pyreverse/diagrams.py
index 5fb7cb9dd..fa88e3816 100644
--- a/pylint/pyreverse/diagrams.py
+++ b/pylint/pyreverse/diagrams.py
@@ -16,7 +16,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
-"""diagram objects"""
+"""Diagram objects."""
import astroid
from astroid import nodes
@@ -25,11 +25,11 @@ from pylint.pyreverse.utils import FilterMixIn, is_interface
class Figure:
- """base class for counter handling"""
+ """Base class for counter handling."""
class Relationship(Figure):
- """A relationship from an object in the diagram to another"""
+ """A relationship from an object in the diagram to another."""
def __init__(self, from_object, to_object, relation_type, name=None):
super().__init__()
@@ -40,7 +40,7 @@ class Relationship(Figure):
class DiagramEntity(Figure):
- """a diagram object, i.e. a label associated to an astroid node"""
+ """A diagram object, i.e. a label associated to an astroid node."""
def __init__(self, title="No name", node=None):
super().__init__()
@@ -49,11 +49,11 @@ class DiagramEntity(Figure):
class PackageEntity(DiagramEntity):
- """A diagram object representing a package"""
+ """A diagram object representing a package."""
class ClassEntity(DiagramEntity):
- """A diagram object representing a class"""
+ """A diagram object representing a class."""
def __init__(self, title, node):
super().__init__(title=title, node=node)
@@ -62,7 +62,7 @@ class ClassEntity(DiagramEntity):
class ClassDiagram(Figure, FilterMixIn):
- """main class diagram handling"""
+ """Main class diagram handling."""
TYPE = "class"
@@ -83,19 +83,19 @@ class ClassDiagram(Figure, FilterMixIn):
)
def add_relationship(self, from_object, to_object, relation_type, name=None):
- """create a relationship"""
+ """Create a relationship."""
rel = Relationship(from_object, to_object, relation_type, name)
self.relationships.setdefault(relation_type, []).append(rel)
def get_relationship(self, from_object, relation_type):
- """return a relationship or None"""
+ """Return a relationship or None."""
for rel in self.relationships.get(relation_type, ()):
if rel.from_object is from_object:
return rel
raise KeyError(relation_type)
def get_attrs(self, node):
- """return visible attributes, possibly with class name"""
+ """Return visible attributes, possibly with class name."""
attrs = []
properties = [
(n, m)
@@ -116,7 +116,7 @@ class ClassDiagram(Figure, FilterMixIn):
return sorted(attrs)
def get_methods(self, node):
- """return visible methods"""
+ """Return visible methods."""
methods = [
m
for m in node.values()
@@ -128,14 +128,14 @@ class ClassDiagram(Figure, FilterMixIn):
return sorted(methods, key=lambda n: n.name)
def add_object(self, title, node):
- """create a diagram object"""
+ """Create a diagram object."""
assert node not in self._nodes
ent = DiagramEntity(title, node)
self._nodes[node] = ent
self.objects.append(ent)
def class_names(self, nodes_lst):
- """return class names if needed in diagram"""
+ """Return class names if needed in diagram."""
names = []
for node in nodes_lst:
if isinstance(node, astroid.Instance):
@@ -151,30 +151,30 @@ class ClassDiagram(Figure, FilterMixIn):
return names
def nodes(self):
- """return the list of underlying nodes"""
+ """Return the list of underlying nodes."""
return self._nodes.keys()
def has_node(self, node):
- """return true if the given node is included in the diagram"""
+ """Return true if the given node is included in the diagram."""
return node in self._nodes
def object_from_node(self, node):
- """return the diagram object mapped to node"""
+ """Return the diagram object mapped to node."""
return self._nodes[node]
def classes(self):
- """return all class nodes in the diagram"""
+ """Return all class nodes in the diagram."""
return [o for o in self.objects if isinstance(o.node, nodes.ClassDef)]
def classe(self, name):
- """return a class by its name, raise KeyError if not found"""
+ """Return a class by its name, raise KeyError if not found."""
for klass in self.classes():
if klass.node.name == name:
return klass
raise KeyError(name)
def extract_relationships(self):
- """Extract relationships between nodes in the diagram"""
+ """Extract relationships between nodes in the diagram."""
for obj in self.classes():
node = obj.node
obj.attrs = self.get_attrs(node)
@@ -215,23 +215,23 @@ class ClassDiagram(Figure, FilterMixIn):
class PackageDiagram(ClassDiagram):
- """package diagram handling"""
+ """Package diagram handling."""
TYPE = "package"
def modules(self):
- """return all module nodes in the diagram"""
+ """Return all module nodes in the diagram."""
return [o for o in self.objects if isinstance(o.node, nodes.Module)]
def module(self, name):
- """return a module by its name, raise KeyError if not found"""
+ """Return a module by its name, raise KeyError if not found."""
for mod in self.modules():
if mod.node.name == name:
return mod
raise KeyError(name)
def get_module(self, name, node):
- """return a module by its name, looking also for relative imports;
+ """Return a module by its name, looking also for relative imports;
raise KeyError if not found
"""
for mod in self.modules():
@@ -247,14 +247,14 @@ class PackageDiagram(ClassDiagram):
raise KeyError(name)
def add_from_depend(self, node, from_module):
- """add dependencies created by from-imports"""
+ """Add dependencies created by from-imports."""
mod_name = node.root().name
obj = self.module(mod_name)
if from_module not in obj.node.depends:
obj.node.depends.append(from_module)
def extract_relationships(self):
- """Extract relationships between nodes in the diagram"""
+ """Extract relationships between nodes in the diagram."""
super().extract_relationships()
for obj in self.classes():
# ownership
diff --git a/pylint/pyreverse/dot_printer.py b/pylint/pyreverse/dot_printer.py
index 59865a0ab..ee19a5b65 100644
--- a/pylint/pyreverse/dot_printer.py
+++ b/pylint/pyreverse/dot_printer.py
@@ -51,7 +51,7 @@ class DotPrinter(Printer):
super().__init__(title, layout, use_automatic_namespace)
def _open_graph(self) -> None:
- """Emit the header lines"""
+ """Emit the header lines."""
self.emit(f'digraph "{self.title}" {{')
if self.layout:
self.emit(f"rankdir={self.layout.value}")
diff --git a/pylint/pyreverse/inspector.py b/pylint/pyreverse/inspector.py
index d3774389e..61c8d1f7e 100644
--- a/pylint/pyreverse/inspector.py
+++ b/pylint/pyreverse/inspector.py
@@ -71,17 +71,17 @@ class IdGeneratorMixIn:
self.id_count = start_value
def init_counter(self, start_value=0):
- """init the id counter"""
+ """Init the id counter."""
self.id_count = start_value
def generate_id(self):
- """generate a new identifier"""
+ """Generate a new identifier."""
self.id_count += 1
return self.id_count
class Project:
- """a project handle a set of modules / packages"""
+ """A project handle a set of modules / packages."""
def __init__(self, name=""):
self.name = name
@@ -143,7 +143,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
self.project = project
def visit_project(self, node: Project) -> None:
- """visit a pyreverse.utils.Project node
+ """Visit a pyreverse.utils.Project node.
* optionally tag the node with a unique id
"""
@@ -153,7 +153,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
self.visit(module)
def visit_module(self, node: nodes.Module) -> None:
- """visit an astroid.Module node
+ """Visit an astroid.Module node.
* set the locals_type mapping
* set the depends mapping
@@ -167,7 +167,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
node.uid = self.generate_id()
def visit_classdef(self, node: nodes.ClassDef) -> None:
- """visit an astroid.Class node
+ """Visit an astroid.Class node.
* set the locals_type and instance_attrs_type mappings
* set the implements list and build it
@@ -196,7 +196,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
node.implements = []
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
- """visit an astroid.Function node
+ """Visit an astroid.Function node.
* set the locals_type mapping
* optionally tag the node with a unique id
@@ -213,7 +213,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
link_function = visit_functiondef
def visit_assignname(self, node: nodes.AssignName) -> None:
- """visit an astroid.AssignName node
+ """Visit an astroid.AssignName node.
handle locals_type
"""
@@ -244,7 +244,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
@staticmethod
def handle_assignattr_type(node, parent):
- """handle an astroid.assignattr node
+ """Handle an astroid.assignattr node.
handle instance_attrs_type
"""
@@ -254,7 +254,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
)
def visit_import(self, node: nodes.Import) -> None:
- """visit an astroid.Import node
+ """Visit an astroid.Import node.
resolve module dependencies
"""
@@ -264,7 +264,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
self._imported_module(node, name[0], relative)
def visit_importfrom(self, node: nodes.ImportFrom) -> None:
- """visit an astroid.ImportFrom node
+ """Visit an astroid.ImportFrom node.
resolve module dependencies
"""
@@ -288,7 +288,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
self._imported_module(node, fullname, relative)
def compute_module(self, context_name, mod_path):
- """return true if the module should be added to dependencies"""
+ """Return true if the module should be added to dependencies."""
package_dir = os.path.dirname(self.project.path)
if context_name == mod_path:
return 0
@@ -297,7 +297,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
return 0
def _imported_module(self, node, mod_path, relative):
- """Notify an imported module, used to analyze dependencies"""
+ """Notify an imported module, used to analyze dependencies."""
module = node.root()
context_name = module.name
if relative:
@@ -314,7 +314,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor):
def project_from_files(
files, func_wrapper=_astroid_wrapper, project_name="no name", black_list=("CVS",)
):
- """return a Project from a list of files or modules"""
+ """Return a Project from a list of files or modules."""
# build the project representation
astroid_manager = astroid.manager.AstroidManager()
project = Project(project_name)
diff --git a/pylint/pyreverse/main.py b/pylint/pyreverse/main.py
index f96c07a59..e955388cb 100644
--- a/pylint/pyreverse/main.py
+++ b/pylint/pyreverse/main.py
@@ -20,7 +20,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
-"""%prog [options] <packages>
+"""%prog [options] <packages>.
create UML diagrams for classes and modules in <packages>
"""
@@ -197,7 +197,7 @@ OPTIONS = (
class Run(ConfigurationMixIn):
- """base class providing common behaviour for pyreverse commands"""
+ """Base class providing common behaviour for pyreverse commands."""
options = OPTIONS
@@ -218,7 +218,7 @@ class Run(ConfigurationMixIn):
sys.exit(self.run(args))
def run(self, args):
- """checking arguments and run project"""
+ """Checking arguments and run project."""
if not args:
print(self.help())
return 1
diff --git a/pylint/pyreverse/mermaidjs_printer.py b/pylint/pyreverse/mermaidjs_printer.py
index bf12fa2ec..014041993 100644
--- a/pylint/pyreverse/mermaidjs_printer.py
+++ b/pylint/pyreverse/mermaidjs_printer.py
@@ -3,7 +3,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
-"""Class to generate files in mermaidjs format"""
+"""Class to generate files in mermaidjs format."""
from typing import Dict, Optional
from pylint.pyreverse.printer import EdgeType, NodeProperties, NodeType, Printer
@@ -11,7 +11,7 @@ from pylint.pyreverse.utils import get_annotation_label
class MermaidJSPrinter(Printer):
- """Printer for MermaidJS diagrams"""
+ """Printer for MermaidJS diagrams."""
DEFAULT_COLOR = "black"
@@ -28,7 +28,7 @@ class MermaidJSPrinter(Printer):
}
def _open_graph(self) -> None:
- """Emit the header lines"""
+ """Emit the header lines."""
self.emit("classDiagram")
self._inc_indent()
@@ -82,7 +82,7 @@ class MermaidJSPrinter(Printer):
class HTMLMermaidJSPrinter(MermaidJSPrinter):
- """Printer for MermaidJS diagrams wrapped in a html boilerplate"""
+ """Printer for MermaidJS diagrams wrapped in a html boilerplate."""
HTML_OPEN_BOILERPLATE = """<html>
<body>
diff --git a/pylint/pyreverse/plantuml_printer.py b/pylint/pyreverse/plantuml_printer.py
index be49c51eb..5693e626f 100644
--- a/pylint/pyreverse/plantuml_printer.py
+++ b/pylint/pyreverse/plantuml_printer.py
@@ -11,7 +11,7 @@ from pylint.pyreverse.utils import get_annotation_label
class PlantUmlPrinter(Printer):
- """Printer for PlantUML diagrams"""
+ """Printer for PlantUML diagrams."""
DEFAULT_COLOR = "black"
@@ -28,7 +28,7 @@ class PlantUmlPrinter(Printer):
}
def _open_graph(self) -> None:
- """Emit the header lines"""
+ """Emit the header lines."""
self.emit("@startuml " + self.title)
if not self.use_automatic_namespace:
self.emit("set namespaceSeparator none")
diff --git a/pylint/pyreverse/printer.py b/pylint/pyreverse/printer.py
index 0fdee79fd..559e456be 100644
--- a/pylint/pyreverse/printer.py
+++ b/pylint/pyreverse/printer.py
@@ -46,7 +46,7 @@ class NodeProperties(NamedTuple):
class Printer(ABC):
- """Base class defining the interface for a printer"""
+ """Base class defining the interface for a printer."""
def __init__(
self,
@@ -62,11 +62,11 @@ class Printer(ABC):
self._open_graph()
def _inc_indent(self) -> None:
- """increment indentation"""
+ """Increment indentation."""
self._indent += " "
def _dec_indent(self) -> None:
- """decrement indentation"""
+ """Decrement indentation."""
self._indent = self._indent[:-2]
@abstractmethod
diff --git a/pylint/pyreverse/utils.py b/pylint/pyreverse/utils.py
index 594c52c5b..5cb4138e7 100644
--- a/pylint/pyreverse/utils.py
+++ b/pylint/pyreverse/utils.py
@@ -19,7 +19,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
-"""Generic classes/functions for pyreverse core/extensions. """
+"""Generic classes/functions for pyreverse core/extensions."""
import os
import re
import shutil
@@ -47,7 +47,7 @@ def get_default_options():
def insert_default_options():
- """insert default options to sys.argv"""
+ """Insert default options to sys.argv."""
options = get_default_options()
options.reverse()
for arg in options:
@@ -61,7 +61,7 @@ PROTECTED = re.compile(r"^_\w*$")
def get_visibility(name):
- """return the visibility from a name: public, protected, private or special"""
+ """Return the visibility from a name: public, protected, private or special."""
if SPECIAL.match(name):
visibility = "special"
elif PRIVATE.match(name):
@@ -79,14 +79,14 @@ FINAL = re.compile(r"^[^\W\da-z]*$")
def is_abstract(node):
- """return true if the given class node correspond to an abstract class
+ """Return true if the given class node correspond to an abstract class
definition
"""
return ABSTRACT.match(node.name)
def is_final(node):
- """return true if the given class/function node correspond to final
+ """Return true if the given class/function node correspond to final
definition
"""
return FINAL.match(node.name)
@@ -123,10 +123,10 @@ VIS_MOD = {
class FilterMixIn:
- """filter nodes according to a mode and nodes' visibility"""
+ """Filter nodes according to a mode and nodes' visibility."""
def __init__(self, mode):
- "init filter modes"
+ """Init filter modes."""
__mode = 0
for nummod in mode.split("+"):
try:
@@ -136,13 +136,13 @@ class FilterMixIn:
self.__mode = __mode
def show_attr(self, node):
- """return true if the node should be treated"""
+ """Return true if the node should be treated."""
visibility = get_visibility(getattr(node, "name", node))
return not self.__mode & VIS_MOD[visibility]
class ASTWalker:
- """a walker visiting a tree in preorder, calling on the handler:
+ """A walker visiting a tree in preorder, calling on the handler:.
* visit_<class name> on entering a node, where class name is the class of
the node in lower case
@@ -156,7 +156,7 @@ class ASTWalker:
self._cache = {}
def walk(self, node, _done=None):
- """walk on the tree from <node>, getting callbacks from handler"""
+ """Walk on the tree from <node>, getting callbacks from handler."""
if _done is None:
_done = set()
if node in _done:
@@ -170,7 +170,7 @@ class ASTWalker:
assert node.parent is not node
def get_callbacks(self, node):
- """get callbacks from handler for the visited node"""
+ """Get callbacks from handler for the visited node."""
klass = node.__class__
methods = self._cache.get(klass)
if methods is None:
@@ -188,27 +188,27 @@ class ASTWalker:
return e_method, l_method
def visit(self, node):
- """walk on the tree from <node>, getting callbacks from handler"""
+ """Walk on the tree from <node>, getting callbacks from handler."""
method = self.get_callbacks(node)[0]
if method is not None:
method(node)
def leave(self, node):
- """walk on the tree from <node>, getting callbacks from handler"""
+ """Walk on the tree from <node>, getting callbacks from handler."""
method = self.get_callbacks(node)[1]
if method is not None:
method(node)
class LocalsVisitor(ASTWalker):
- """visit a project by traversing the locals dictionary"""
+ """Visit a project by traversing the locals dictionary."""
def __init__(self):
super().__init__(self)
self._visited = set()
def visit(self, node):
- """launch the visit starting from the given node"""
+ """Launch the visit starting from the given node."""
if node in self._visited:
return None
@@ -236,7 +236,7 @@ def get_annotation_label(ann: Union[nodes.Name, nodes.Subscript]) -> str:
def get_annotation(
node: Union[nodes.AssignAttr, nodes.AssignName]
) -> Optional[Union[nodes.Name, nodes.Subscript]]:
- """return the annotation for `node`"""
+ """Return the annotation for `node`."""
ann = None
if isinstance(node.parent, nodes.AnnAssign):
ann = node.parent.annotation
diff --git a/pylint/pyreverse/vcg_printer.py b/pylint/pyreverse/vcg_printer.py
index ccaa55321..f7e2a4665 100644
--- a/pylint/pyreverse/vcg_printer.py
+++ b/pylint/pyreverse/vcg_printer.py
@@ -187,7 +187,7 @@ ORIENTATION: Dict[Layout, str] = {
class VCGPrinter(Printer):
def _open_graph(self) -> None:
- """Emit the header lines"""
+ """Emit the header lines."""
self.emit("graph:{\n")
self._inc_indent()
self._write_attributes(
@@ -269,7 +269,7 @@ class VCGPrinter(Printer):
self.emit("}")
def _write_attributes(self, attributes_dict: Mapping[str, Any], **args) -> None:
- """write graph, node or edge attributes"""
+ """Write graph, node or edge attributes."""
for key, value in args.items():
try:
_type = attributes_dict[key]
diff --git a/pylint/pyreverse/writer.py b/pylint/pyreverse/writer.py
index fa2ce1836..86a03ac7e 100644
--- a/pylint/pyreverse/writer.py
+++ b/pylint/pyreverse/writer.py
@@ -16,7 +16,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
-"""Utilities for creating VCG and Dot diagrams"""
+"""Utilities for creating VCG and Dot diagrams."""
import itertools
import os
@@ -36,7 +36,7 @@ from pylint.pyreverse.utils import is_exception
class DiagramWriter:
- """base class for writing project diagrams"""
+ """Base class for writing project diagrams."""
def __init__(self, config):
self.config = config
@@ -68,7 +68,7 @@ class DiagramWriter:
self.used_colors = {}
def write(self, diadefs):
- """write files for <project> according to <diadefs>"""
+ """Write files for <project> according to <diadefs>."""
for diagram in diadefs:
basename = diagram.title.strip().replace(" ", "_")
file_name = f"{basename}.{self.config.output_format}"
@@ -82,7 +82,7 @@ class DiagramWriter:
self.save()
def write_packages(self, diagram: PackageDiagram) -> None:
- """write a package diagram"""
+ """Write a package diagram."""
# sorted to get predictable (hence testable) results
for module in sorted(diagram.modules(), key=lambda x: x.title):
module.fig_id = module.node.qname()
@@ -100,7 +100,7 @@ class DiagramWriter:
)
def write_classes(self, diagram: ClassDiagram) -> None:
- """write a class diagram"""
+ """Write a class diagram."""
# sorted to get predictable (hence testable) results
for obj in sorted(diagram.objects, key=lambda x: x.title):
obj.fig_id = obj.node.qname()
@@ -132,19 +132,19 @@ class DiagramWriter:
)
def set_printer(self, file_name: str, basename: str) -> None:
- """set printer"""
+ """Set printer."""
self.printer = self.printer_class(basename)
self.file_name = file_name
def get_package_properties(self, obj: PackageEntity) -> NodeProperties:
- """get label and shape for packages."""
+ """Get label and shape for packages."""
return NodeProperties(
label=obj.title,
color=self.get_shape_color(obj) if self.config.colorized else "black",
)
def get_class_properties(self, obj: ClassEntity) -> NodeProperties:
- """get label and shape for classes."""
+ """Get label and shape for classes."""
properties = NodeProperties(
label=obj.title,
attrs=obj.attrs if not self.config.only_classnames else None,
@@ -155,7 +155,7 @@ class DiagramWriter:
return properties
def get_shape_color(self, obj: DiagramEntity) -> str:
- """get shape color"""
+ """Get shape color."""
qualified_name = obj.node.qname()
if modutils.is_standard_module(qualified_name.split(".", maxsplit=1)[0]):
return "grey"
@@ -171,5 +171,5 @@ class DiagramWriter:
return self.used_colors[base_name]
def save(self) -> None:
- """write to disk"""
+ """Write to disk."""
self.printer.generate(self.file_name)
diff --git a/pylint/reporters/__init__.py b/pylint/reporters/__init__.py
index 420154d54..92b6bae21 100644
--- a/pylint/reporters/__init__.py
+++ b/pylint/reporters/__init__.py
@@ -21,7 +21,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
-"""utilities methods and classes for reporters"""
+"""Utilities methods and classes for reporters."""
from typing import TYPE_CHECKING
from pylint import utils
@@ -36,7 +36,7 @@ if TYPE_CHECKING:
def initialize(linter: "PyLinter") -> None:
- """initialize linter with reporters in this package"""
+ """Initialize linter with reporters in this package."""
utils.register_plugins(linter, __path__[0])
diff --git a/pylint/reporters/base_reporter.py b/pylint/reporters/base_reporter.py
index 7ee55beff..570175567 100644
--- a/pylint/reporters/base_reporter.py
+++ b/pylint/reporters/base_reporter.py
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
class BaseReporter:
- """base class for reporters
+ """Base class for reporters.
symbols: show short symbolic names for messages.
"""
@@ -24,7 +24,7 @@ class BaseReporter:
extension = ""
name = "base"
- """Name of the reporter"""
+ """Name of the reporter."""
def __init__(self, output: Optional[TextIO] = None) -> None:
self.linter: "PyLinter"
@@ -39,7 +39,7 @@ class BaseReporter:
self.messages.append(msg)
def set_output(self, output: Optional[TextIO] = None) -> None:
- """set output stream"""
+ """Set output stream."""
# pylint: disable-next=fixme
# TODO: Remove this method after depreciation
warn(
@@ -49,11 +49,11 @@ class BaseReporter:
self.out = output or sys.stdout
def writeln(self, string: str = "") -> None:
- """write a line in the output buffer"""
+ """Write a line in the output buffer."""
print(string, file=self.out)
def display_reports(self, layout: "Section") -> None:
- """display results encapsulated in the layout tree"""
+ """Display results encapsulated in the layout tree."""
self.section = 0
if layout.report_id:
if isinstance(layout.children[0].children[0], Text):
@@ -63,11 +63,11 @@ class BaseReporter:
self._display(layout)
def _display(self, layout: "Section") -> None:
- """display the layout"""
+ """Display the layout."""
raise NotImplementedError()
def display_messages(self, layout: Optional["Section"]) -> None:
- """Hook for displaying the messages of the reporter
+ """Hook for displaying the messages of the reporter.
This will be called whenever the underlying messages
needs to be displayed. For some reporters, it probably
diff --git a/pylint/reporters/collecting_reporter.py b/pylint/reporters/collecting_reporter.py
index 70f313bb3..9b787342a 100644
--- a/pylint/reporters/collecting_reporter.py
+++ b/pylint/reporters/collecting_reporter.py
@@ -9,7 +9,7 @@ if TYPE_CHECKING:
class CollectingReporter(BaseReporter):
- """collects messages"""
+ """Collects messages."""
name = "collector"
diff --git a/pylint/reporters/json_reporter.py b/pylint/reporters/json_reporter.py
index 8761979aa..5c2074773 100644
--- a/pylint/reporters/json_reporter.py
+++ b/pylint/reporters/json_reporter.py
@@ -12,7 +12,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
-"""JSON reporter"""
+"""JSON reporter."""
import json
from typing import TYPE_CHECKING, Optional
@@ -32,7 +32,7 @@ class JSONReporter(BaseReporter):
extension = "json"
def display_messages(self, layout: Optional["Section"]) -> None:
- """Launch layouts display"""
+ """Launch layouts display."""
json_dumpable = [
{
"type": msg.category,
diff --git a/pylint/reporters/multi_reporter.py b/pylint/reporters/multi_reporter.py
index 61740908d..a68c8c423 100644
--- a/pylint/reporters/multi_reporter.py
+++ b/pylint/reporters/multi_reporter.py
@@ -18,7 +18,7 @@ PyLinter = Any
class MultiReporter:
- """Reports messages and layouts in plain text"""
+ """Reports messages and layouts in plain text."""
__implements__ = IReporter
name = "_internal_multi_reporter"
@@ -80,22 +80,22 @@ class MultiReporter:
rep.handle_message(msg)
def writeln(self, string: str = "") -> None:
- """write a line in the output buffer"""
+ """Write a line in the output buffer."""
for rep in self._sub_reporters:
rep.writeln(string)
def display_reports(self, layout: "Section") -> None:
- """display results encapsulated in the layout tree"""
+ """Display results encapsulated in the layout tree."""
for rep in self._sub_reporters:
rep.display_reports(layout)
def display_messages(self, layout: Optional["Section"]) -> None:
- """hook for displaying the messages of the reporter"""
+ """Hook for displaying the messages of the reporter."""
for rep in self._sub_reporters:
rep.display_messages(layout)
def on_set_current_module(self, module: str, filepath: Optional[str]) -> None:
- """hook called when a module starts to be analysed"""
+ """Hook called when a module starts to be analysed."""
for rep in self._sub_reporters:
rep.on_set_current_module(module, filepath)
@@ -104,6 +104,6 @@ class MultiReporter:
stats: LinterStats,
previous_stats: LinterStats,
) -> None:
- """hook called when a module finished analyzing"""
+ """Hook called when a module finished analyzing."""
for rep in self._sub_reporters:
rep.on_close(stats, previous_stats)
diff --git a/pylint/reporters/reports_handler_mix_in.py b/pylint/reporters/reports_handler_mix_in.py
index 245d2ded1..01d9947fd 100644
--- a/pylint/reporters/reports_handler_mix_in.py
+++ b/pylint/reporters/reports_handler_mix_in.py
@@ -34,13 +34,13 @@ class ReportsHandlerMixIn:
self._reports_state: Dict[str, bool] = {}
def report_order(self) -> MutableSequence["BaseChecker"]:
- """Return a list of reporters"""
+ """Return a list of reporters."""
return list(self._reports)
def register_report(
self, reportid: str, r_title: str, r_cb: Callable, checker: "BaseChecker"
) -> None:
- """Register a report
+ """Register a report.
:param reportid: The unique identifier for the report
:param r_title: The report's title
@@ -51,12 +51,12 @@ class ReportsHandlerMixIn:
self._reports[checker].append((reportid, r_title, r_cb))
def enable_report(self, reportid: str) -> None:
- """Enable 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
@@ -69,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 b0db63f11..6743ab5b1 100644
--- a/pylint/reporters/text.py
+++ b/pylint/reporters/text.py
@@ -19,7 +19,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
-"""Plain text reporters:
+"""Plain text reporters:.
:text: the default one grouping messages by module
:colorized: an ANSI colorized text reporter
@@ -53,7 +53,7 @@ if TYPE_CHECKING:
class MessageStyle(NamedTuple):
- """Styling of a message"""
+ """Styling of a message."""
color: Optional[str]
"""The color name (see `ANSI_COLORS` for available values)
@@ -93,7 +93,7 @@ ANSI_COLORS = {
def _get_ansi_code(msg_style: MessageStyle) -> str:
- """return ansi escape code corresponding to color and style
+ """Return ansi escape code corresponding to color and style.
:param msg_style: the message style
@@ -173,7 +173,7 @@ def colorize_ansi(
class TextReporter(BaseReporter):
- """Reports messages and layouts in plain text"""
+ """Reports messages and layouts in plain text."""
__implements__ = IReporter
name = "text"
@@ -185,7 +185,7 @@ class TextReporter(BaseReporter):
self._modules: Set[str] = set()
self._template = self.line_format
self._fixed_template = self.line_format
- """The output format template with any unrecognized arguments removed"""
+ """The output format template with any unrecognized arguments removed."""
def on_set_current_module(self, module: str, filepath: Optional[str]) -> None:
"""Set the format template to be used and check for unrecognized arguments."""
@@ -210,7 +210,7 @@ class TextReporter(BaseReporter):
self._fixed_template = template
def write_message(self, msg: Message) -> None:
- """Convenience method to write a formatted message with class default template"""
+ """Convenience method to write a formatted message with class default template."""
self_dict = msg._asdict()
for key in ("end_line", "end_column"):
self_dict[key] = self_dict[key] or ""
@@ -218,7 +218,7 @@ class TextReporter(BaseReporter):
self.writeln(self._fixed_template.format(**self_dict))
def handle_message(self, msg: Message) -> None:
- """manage message of different type and in the context of path"""
+ """Manage message of different type and in the context of path."""
if msg.module not in self._modules:
if msg.module:
self.writeln(f"************* Module {msg.module}")
@@ -228,13 +228,13 @@ class TextReporter(BaseReporter):
self.write_message(msg)
def _display(self, layout: "Section") -> None:
- """launch layouts display"""
+ """Launch layouts display."""
print(file=self.out)
TextWriter().format(layout, self.out)
class ParseableTextReporter(TextReporter):
- """a reporter very similar to TextReporter, but display messages in a form
+ """A reporter very similar to TextReporter, but display messages in a form
recognized by most text editors :
<filename>:<linenum>:<msg>
@@ -252,14 +252,14 @@ class ParseableTextReporter(TextReporter):
class VSTextReporter(ParseableTextReporter):
- """Visual studio text reporter"""
+ """Visual studio text reporter."""
name = "msvs"
line_format = "{path}({line}): [{msg_id}({symbol}){obj}] {msg}"
class ColorizedTextReporter(TextReporter):
- """Simple TextReporter that colorizes text output"""
+ """Simple TextReporter that colorizes text output."""
name = "colorized"
COLOR_MAPPING: ColorMappingDict = {
@@ -324,11 +324,11 @@ class ColorizedTextReporter(TextReporter):
self.out = colorama.AnsiToWin32(self.out)
def _get_decoration(self, msg_id: str) -> MessageStyle:
- """Returns the message style as defined in self.color_mapping"""
+ """Returns the message style as defined in self.color_mapping."""
return self.color_mapping.get(msg_id[0]) or MessageStyle(None)
def handle_message(self, msg: Message) -> None:
- """manage message of different types, and colorize output
+ """Manage message of different types, and colorize output
using ansi escape codes
"""
if msg.module not in self._modules:
diff --git a/pylint/reporters/ureports/base_writer.py b/pylint/reporters/ureports/base_writer.py
index e87acd7ea..dba57c86f 100644
--- a/pylint/reporters/ureports/base_writer.py
+++ b/pylint/reporters/ureports/base_writer.py
@@ -30,10 +30,10 @@ if TYPE_CHECKING:
class BaseWriter:
- """base class for ureport writers"""
+ """Base class for ureport writers."""
def format(self, layout, stream: TextIO = sys.stdout, encoding=None) -> None:
- """format and write the given layout into the stream object
+ """Format and write the given layout into the stream object.
unicode policy: unicode strings may be found in the layout;
try to call 'stream.write' with it, but give it back encoded using
@@ -50,29 +50,29 @@ class BaseWriter:
def format_children(
self, layout: Union["EvaluationSection", "Paragraph", "Section"]
) -> None:
- """recurse on the layout children and call their accept method
+ """Recurse on the layout children and call their accept method
(see the Visitor pattern)
"""
for child in getattr(layout, "children", ()):
child.accept(self)
def writeln(self, string: str = "") -> None:
- """write a line in the output buffer"""
+ """Write a line in the output buffer."""
self.write(string + "\n")
def write(self, string: str) -> None:
- """write a string in the output buffer"""
+ """Write a string in the output buffer."""
self.out.write(string)
def begin_format(self) -> None:
- """begin to format a layout"""
+ """Begin to format a layout."""
self.section = 0
def end_format(self) -> None:
- """Finished formatting a layout"""
+ """Finished formatting a layout."""
def get_table_content(self, table: "Table") -> List[List[str]]:
- """trick to get table content without actually writing it
+ """Trick to get table content without actually writing it.
return an aligned list of lists containing table cells values as string
"""
@@ -89,7 +89,7 @@ class BaseWriter:
return result
def compute_content(self, layout) -> Iterator[str]:
- """trick to compute the formatting of children layout before actually
+ """Trick to compute the formatting of children layout before actually
writing it
return an iterator on strings (one for each child element)
diff --git a/pylint/reporters/ureports/nodes.py b/pylint/reporters/ureports/nodes.py
index 280f97528..a4e32f81e 100644
--- a/pylint/reporters/ureports/nodes.py
+++ b/pylint/reporters/ureports/nodes.py
@@ -39,7 +39,7 @@ class VNode:
class BaseLayout(VNode):
- """base container node
+ """Base container node.
attributes
* children : components in this table (i.e. the table's cells)
@@ -54,25 +54,25 @@ class BaseLayout(VNode):
self.add_text(child)
def append(self, child: VNode) -> None:
- """add a node to children"""
+ """Add a node to children."""
assert child not in self.parents()
self.children.append(child)
child.parent = self
def insert(self, index: int, child: VNode) -> None:
- """insert a child node"""
+ """Insert a child node."""
self.children.insert(index, child)
child.parent = self
def parents(self) -> List["BaseLayout"]:
- """return the ancestor nodes"""
+ """Return the ancestor nodes."""
assert self.parent is not self
if self.parent is None:
return []
return [self.parent] + self.parent.parents()
def add_text(self, text: str) -> None:
- """shortcut to add text data"""
+ """Shortcut to add text data."""
self.children.append(Text(text))
@@ -80,7 +80,7 @@ class BaseLayout(VNode):
class Text(VNode):
- """a text portion
+ """A text portion.
attributes :
* data : the text value as an encoded or unicode string
@@ -93,7 +93,7 @@ class Text(VNode):
class VerbatimText(Text):
- """a verbatim text, display the raw data
+ """A verbatim text, display the raw data.
attributes :
* data : the text value as an encoded or unicode string
@@ -104,7 +104,7 @@ class VerbatimText(Text):
class Section(BaseLayout):
- """a section
+ """A section.
attributes :
* BaseLayout attributes
@@ -143,7 +143,7 @@ class EvaluationSection(Section):
class Title(BaseLayout):
- """a title
+ """A title.
attributes :
* BaseLayout attributes
@@ -153,7 +153,7 @@ class Title(BaseLayout):
class Paragraph(BaseLayout):
- """a simple text paragraph
+ """A simple text paragraph.
attributes :
* BaseLayout attributes
@@ -163,7 +163,7 @@ class Paragraph(BaseLayout):
class Table(BaseLayout):
- """some tabular data
+ """Some tabular data.
attributes :
* BaseLayout attributes
diff --git a/pylint/reporters/ureports/text_writer.py b/pylint/reporters/ureports/text_writer.py
index 392c86cc8..cb80e6771 100644
--- a/pylint/reporters/ureports/text_writer.py
+++ b/pylint/reporters/ureports/text_writer.py
@@ -10,7 +10,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
-"""Text formatting drivers for ureports"""
+"""Text formatting drivers for ureports."""
from typing import TYPE_CHECKING, List
@@ -32,7 +32,7 @@ BULLETS = ["*", "-"]
class TextWriter(BaseWriter):
- """format layouts as text
+ """Format layouts as text
(ReStructured inspiration but not totally handled yet)
"""
@@ -41,7 +41,7 @@ class TextWriter(BaseWriter):
self.list_level = 0
def visit_section(self, layout: "Section") -> None:
- """display a section as text"""
+ """Display a section as text."""
self.section += 1
self.writeln()
self.format_children(layout)
@@ -64,12 +64,12 @@ class TextWriter(BaseWriter):
print("FIXME TITLE TOO DEEP. TURNING TITLE INTO TEXT")
def visit_paragraph(self, layout: "Paragraph") -> None:
- """enter a paragraph"""
+ """Enter a paragraph."""
self.format_children(layout)
self.writeln()
def visit_table(self, layout: "Table") -> None:
- """display a table as text"""
+ """Display a table as text."""
table_content = self.get_table_content(layout)
# get columns width
cols_width = [0] * len(table_content[0])
@@ -82,7 +82,7 @@ class TextWriter(BaseWriter):
def default_table(
self, layout: "Table", table_content: List[List[str]], cols_width: List[int]
) -> None:
- """format a table"""
+ """Format a table."""
cols_width = [size + 1 for size in cols_width]
format_strings = " ".join(["%%-%ss"] * len(cols_width))
format_strings %= tuple(cols_width)
@@ -103,12 +103,12 @@ class TextWriter(BaseWriter):
self.write(table_linesep)
def visit_verbatimtext(self, layout: "VerbatimText") -> None:
- """display a verbatim layout as text (so difficult ;)"""
+ """Display a verbatim layout as text (so difficult ;)."""
self.writeln("::\n")
for line in layout.data.splitlines():
self.writeln(" " + line)
self.writeln()
def visit_text(self, layout: "Text") -> None:
- """add some text"""
+ """Add some text."""
self.write(f"{layout.data}")
diff --git a/pylint/testutils/__init__.py b/pylint/testutils/__init__.py
index 53e301da3..2b392d058 100644
--- a/pylint/testutils/__init__.py
+++ b/pylint/testutils/__init__.py
@@ -28,7 +28,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
-"""Functional/non regression tests for pylint"""
+"""Functional/non regression tests for pylint."""
__all__ = [
"_get_tests_info",
diff --git a/pylint/testutils/checker_test_case.py b/pylint/testutils/checker_test_case.py
index 5fabf97c5..f8324b9a9 100644
--- a/pylint/testutils/checker_test_case.py
+++ b/pylint/testutils/checker_test_case.py
@@ -88,7 +88,7 @@ class CheckerTestCase:
)
def walk(self, node):
- """recursive walk on the given node"""
+ """Recursive walk on the given node."""
walker = ASTWalker(linter)
walker.add_checker(self.checker)
walker.walk(node)
diff --git a/pylint/testutils/configuration_test.py b/pylint/testutils/configuration_test.py
index 4e6f265bb..b699f3242 100644
--- a/pylint/testutils/configuration_test.py
+++ b/pylint/testutils/configuration_test.py
@@ -55,7 +55,7 @@ EXPECTED_CONF_REMOVE_KEY = "functional_remove"
def get_expected_configuration(
configuration_path: str, default_configuration: PylintConfiguration
) -> PylintConfiguration:
- """Get the expected parsed configuration of a configuration functional test"""
+ """Get the expected parsed configuration of a configuration functional test."""
result = copy.deepcopy(default_configuration)
config_as_json = get_expected_or_default(
configuration_path, suffix="result.json", default="{}"
diff --git a/pylint/testutils/get_test_info.py b/pylint/testutils/get_test_info.py
index 9900c7326..32498b8ba 100644
--- a/pylint/testutils/get_test_info.py
+++ b/pylint/testutils/get_test_info.py
@@ -11,7 +11,7 @@ from pylint.testutils.constants import SYS_VERS_STR
def _get_tests_info(
input_dir: str, msg_dir: str, prefix: str, suffix: str
) -> List[Tuple[str, str]]:
- """get python input examples and output messages
+ """Get python input examples and output messages.
We use following conventions for input files and messages:
for different inputs:
diff --git a/pylint/testutils/lint_module_test.py b/pylint/testutils/lint_module_test.py
index 9bbf00d2f..ed20ed860 100644
--- a/pylint/testutils/lint_module_test.py
+++ b/pylint/testutils/lint_module_test.py
@@ -259,7 +259,7 @@ class LintModuleTest:
expected_output: List[OutputLine],
actual_output: List[OutputLine],
) -> None:
- """This is a function because we want to be able to update the text in LintModuleOutputUpdate"""
+ """This is a function because we want to be able to update the text in LintModuleOutputUpdate."""
assert expected_output == actual_output, self.error_msg_for_unequal_output(
expected_output, actual_output
)
diff --git a/pylint/testutils/output_line.py b/pylint/testutils/output_line.py
index 1061854bc..e851ccfbe 100644
--- a/pylint/testutils/output_line.py
+++ b/pylint/testutils/output_line.py
@@ -76,7 +76,7 @@ class OutputLine(NamedTuple):
@classmethod
def from_msg(cls, msg: Message, check_endline: bool = True) -> "OutputLine":
- """Create an OutputLine from a Pylint Message"""
+ """Create an OutputLine from a Pylint Message."""
column = cls._get_column(msg.column)
end_line = cls._get_py38_none_value(msg.end_line, check_endline)
end_column = cls._get_py38_none_value(msg.end_column, check_endline)
@@ -182,7 +182,7 @@ class OutputLine(NamedTuple):
@staticmethod
def _value_to_optional_int(value: Optional[str]) -> Optional[int]:
- """Checks if a (stringified) value should be None or a Python integer"""
+ """Checks if a (stringified) value should be None or a Python integer."""
if value == "None" or not value:
return None
return int(value)
diff --git a/pylint/testutils/primer.py b/pylint/testutils/primer.py
index b8b33ae3e..558ad582e 100644
--- a/pylint/testutils/primer.py
+++ b/pylint/testutils/primer.py
@@ -8,25 +8,25 @@ PRIMER_DIRECTORY_PATH = Path(".pylint_primer_tests")
class PackageToLint:
- """Represents data about a package to be tested during primer tests"""
+ """Represents data about a package to be tested during primer tests."""
url: str
- """URL of the repository to clone"""
+ """URL of the repository to clone."""
branch: str
- """Branch of the repository to clone"""
+ """Branch of the repository to clone."""
directories: List[str]
- """Directories within the repository to run pylint over"""
+ """Directories within the repository to run pylint over."""
commit: Optional[str]
- """Commit hash to pin the repository on"""
+ """Commit hash to pin the repository on."""
pylint_additional_args: List[str]
- """Arguments to give to pylint"""
+ """Arguments to give to pylint."""
pylintrc_relpath: Optional[str]
- """Path relative to project's main directory to the pylintrc if it exists"""
+ """Path relative to project's main directory to the pylintrc if it exists."""
def __init__(
self,
@@ -52,13 +52,13 @@ class PackageToLint:
@property
def clone_directory(self) -> Path:
- """Directory to clone repository into"""
+ """Directory to clone repository into."""
clone_name = "/".join(self.url.split("/")[-2:]).replace(".git", "")
return PRIMER_DIRECTORY_PATH / clone_name
@property
def paths_to_lint(self) -> List[str]:
- """The paths we need to lint"""
+ """The paths we need to lint."""
return [str(self.clone_directory / path) for path in self.directories]
@property
@@ -70,7 +70,7 @@ class PackageToLint:
return self.paths_to_lint + options + self.pylint_additional_args
def lazy_clone(self) -> None: # pragma: no cover
- """Concatenates the target directory and clones the file
+ """Concatenates the target directory and clones the file.
Not expected to be tested as the primer won't work if it doesn't.
It's tested in the continuous integration primers, only the coverage
diff --git a/pylint/testutils/reporter_for_tests.py b/pylint/testutils/reporter_for_tests.py
index 148777406..0c2b456f3 100644
--- a/pylint/testutils/reporter_for_tests.py
+++ b/pylint/testutils/reporter_for_tests.py
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
class GenericTestReporter(BaseReporter):
- """reporter storing plain text messages"""
+ """Reporter storing plain text messages."""
__implements__ = interfaces.IReporter
out: StringIO
@@ -30,11 +30,11 @@ class GenericTestReporter(BaseReporter):
self.messages: List[Message] = []
def handle_message(self, msg: Message) -> None:
- """Append messages to the list of messages of the reporter"""
+ """Append messages to the list of messages of the reporter."""
self.messages.append(msg)
def finalize(self) -> str:
- """Format and print messages in the context of the path"""
+ """Format and print messages in the context of the path."""
messages: List[str] = []
for msg in self.messages:
obj = ""
@@ -56,7 +56,7 @@ class GenericTestReporter(BaseReporter):
# pylint: enable=unused-argument
def display_reports(self, layout: "Section") -> None:
- """ignore layouts"""
+ """Ignore layouts."""
def _display(self, layout: "Section") -> None:
pass
diff --git a/pylint/typing.py b/pylint/typing.py
index 09e4df126..84c49df55 100644
--- a/pylint/typing.py
+++ b/pylint/typing.py
@@ -12,7 +12,7 @@ else:
class FileItem(NamedTuple):
- """Represents data about a file handled by pylint
+ """Represents data about a file handled by pylint.
Each file item has:
- name: full name of the module
@@ -26,7 +26,7 @@ class FileItem(NamedTuple):
class ModuleDescriptionDict(TypedDict):
- """Represents data about a checked module"""
+ """Represents data about a checked module."""
path: str
name: str
@@ -36,7 +36,7 @@ class ModuleDescriptionDict(TypedDict):
class ErrorDescriptionDict(TypedDict):
- """Represents data about errors collected during checking of a module"""
+ """Represents data about errors collected during checking of a module."""
key: Literal["fatal"]
mod: str
@@ -44,7 +44,7 @@ class ErrorDescriptionDict(TypedDict):
class MessageLocationTuple(NamedTuple):
- """Tuple with information about the location of a to-be-displayed message"""
+ """Tuple with information about the location of a to-be-displayed message."""
abspath: str
path: str
@@ -57,7 +57,7 @@ class MessageLocationTuple(NamedTuple):
class ManagedMessage(NamedTuple):
- """Tuple with information about a managed message of the linter"""
+ """Tuple with information about a managed message of the linter."""
name: Optional[str]
msgid: str
diff --git a/pylint/utils/__init__.py b/pylint/utils/__init__.py
index 58072eece..53d07825e 100644
--- a/pylint/utils/__init__.py
+++ b/pylint/utils/__init__.py
@@ -40,7 +40,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
-"""some various utilities and helper classes, most of them used in the
+"""Some various utilities and helper classes, most of them used in the
main pylint class
"""
diff --git a/pylint/utils/ast_walker.py b/pylint/utils/ast_walker.py
index f846c9c21..f9e573a95 100644
--- a/pylint/utils/ast_walker.py
+++ b/pylint/utils/ast_walker.py
@@ -22,7 +22,7 @@ class ASTWalker:
return any(self.linter.is_message_enabled(m) for m in method.checks_msgs)
def add_checker(self, checker):
- """walk to the checker's dir and collect visit and leave methods"""
+ """Walk to the checker's dir and collect visit and leave methods."""
vcids = set()
lcids = set()
visits = self.visit_events
diff --git a/pylint/utils/docs.py b/pylint/utils/docs.py
index 5b46a0bc1..848a49868 100644
--- a/pylint/utils/docs.py
+++ b/pylint/utils/docs.py
@@ -1,6 +1,6 @@
# 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
-"""Various helper functions to create the docs of a linter object"""
+"""Various helper functions to create the docs of a linter object."""
import sys
from typing import TYPE_CHECKING, Dict, TextIO
@@ -13,7 +13,7 @@ if TYPE_CHECKING:
def _get_checkers_infos(linter: "PyLinter") -> Dict[str, Dict]:
- """Get info from a checker and handle KeyError"""
+ """Get info from a checker and handle KeyError."""
by_checker: Dict[str, Dict] = {}
for checker in linter.get_checkers():
name = checker.name
@@ -34,7 +34,7 @@ def _get_checkers_infos(linter: "PyLinter") -> Dict[str, Dict]:
def _get_checkers_documentation(linter: "PyLinter") -> str:
- """Get documentation for individual checkers"""
+ """Get documentation for individual checkers."""
result = get_rst_title("Pylint global options and switches", "-")
result += """
Pylint provides global options and switches.
@@ -73,5 +73,5 @@ Below is a list of all checkers and their features.
def print_full_documentation(linter: "PyLinter", stream: TextIO = sys.stdout) -> None:
- """Output a full documentation in ReST format"""
+ """Output a full documentation in ReST format."""
print(_get_checkers_documentation(linter)[:-1], file=stream)
diff --git a/pylint/utils/file_state.py b/pylint/utils/file_state.py
index 4252f0154..654cb725b 100644
--- a/pylint/utils/file_state.py
+++ b/pylint/utils/file_state.py
@@ -31,7 +31,7 @@ MessageStateDict = Dict[str, Dict[int, bool]]
class FileState:
- """Hold internal state specific to the currently analyzed file"""
+ """Hold internal state specific to the currently analyzed file."""
def __init__(self, modname: Optional[str] = None) -> None:
self.base_name = modname
@@ -122,7 +122,7 @@ class FileState:
del lines[lineno]
def set_msg_status(self, msg: "MessageDefinition", line: int, status: bool) -> None:
- """Set status (enabled/disable) for a given message at a given line"""
+ """Set status (enabled/disable) for a given message at a given line."""
assert line > 0
try:
self._module_msgs_state[msg.msgid][line] = status
diff --git a/pylint/utils/linterstats.py b/pylint/utils/linterstats.py
index 125954e4e..54b98d533 100644
--- a/pylint/utils/linterstats.py
+++ b/pylint/utils/linterstats.py
@@ -13,7 +13,7 @@ else:
class BadNames(TypedDict):
- """TypedDict to store counts of node types with bad names"""
+ """TypedDict to store counts of node types with bad names."""
argument: int
attr: int
@@ -29,7 +29,7 @@ class BadNames(TypedDict):
class CodeTypeCount(TypedDict):
- """TypedDict to store counts of lines of code types"""
+ """TypedDict to store counts of lines of code types."""
code: int
comment: int
@@ -39,14 +39,14 @@ class CodeTypeCount(TypedDict):
class DuplicatedLines(TypedDict):
- """TypedDict to store counts of lines of duplicated code"""
+ """TypedDict to store counts of lines of duplicated code."""
nb_duplicated_lines: int
percent_duplicated_lines: float
class NodeCount(TypedDict):
- """TypedDict to store counts of different types of nodes"""
+ """TypedDict to store counts of different types of nodes."""
function: int
klass: int
@@ -55,7 +55,7 @@ class NodeCount(TypedDict):
class UndocumentedNodes(TypedDict):
- """TypedDict to store counts of undocumented node types"""
+ """TypedDict to store counts of undocumented node types."""
function: int
klass: int
@@ -64,7 +64,7 @@ class UndocumentedNodes(TypedDict):
class ModuleStats(TypedDict):
- """TypedDict to store counts of types of messages and statements"""
+ """TypedDict to store counts of types of messages and statements."""
convention: int
error: int
@@ -77,7 +77,7 @@ class ModuleStats(TypedDict):
# pylint: disable-next=too-many-instance-attributes
class LinterStats:
- """Class used to linter stats"""
+ """Class used to linter stats."""
def __init__(
self,
@@ -173,13 +173,13 @@ class LinterStats:
"variable",
],
) -> int:
- """Get a bad names node count"""
+ """Get a bad names node count."""
if node_name == "class":
return self.bad_names.get("klass", 0)
return self.bad_names.get(node_name, 0)
def increase_bad_name(self, node_name: str, increase: int) -> None:
- """Increase a bad names node count"""
+ """Increase a bad names node count."""
if node_name not in {
"argument",
"attr",
@@ -217,7 +217,7 @@ class LinterStats:
self.bad_names[node_name] += increase
def reset_bad_names(self) -> None:
- """Resets the bad_names attribute"""
+ """Resets the bad_names attribute."""
self.bad_names = BadNames(
argument=0,
attr=0,
@@ -235,17 +235,17 @@ class LinterStats:
def get_code_count(
self, type_name: Literal["code", "comment", "docstring", "empty", "total"]
) -> int:
- """Get a code type count"""
+ """Get a code type count."""
return self.code_type_count.get(type_name, 0)
def reset_code_count(self) -> None:
- """Resets the code_type_count attribute"""
+ """Resets the code_type_count attribute."""
self.code_type_count = CodeTypeCount(
code=0, comment=0, docstring=0, empty=0, total=0
)
def reset_duplicated_lines(self) -> None:
- """Resets the duplicated_lines attribute"""
+ """Resets the duplicated_lines attribute."""
self.duplicated_lines = DuplicatedLines(
nb_duplicated_lines=0, percent_duplicated_lines=0.0
)
@@ -253,47 +253,47 @@ class LinterStats:
def get_node_count(
self, node_name: Literal["function", "class", "method", "module"]
) -> int:
- """Get a node count while handling some extra conditions"""
+ """Get a node count while handling some extra conditions."""
if node_name == "class":
return self.node_count.get("klass", 0)
return self.node_count.get(node_name, 0)
def reset_node_count(self) -> None:
- """Resets the node count attribute"""
+ """Resets the node count attribute."""
self.node_count = NodeCount(function=0, klass=0, method=0, module=0)
def get_undocumented(
self, node_name: Literal["function", "class", "method", "module"]
) -> float:
- """Get a undocumented node count"""
+ """Get a undocumented node count."""
if node_name == "class":
return self.undocumented["klass"]
return self.undocumented[node_name]
def reset_undocumented(self) -> None:
- """Resets the undocumented attribute"""
+ """Resets the undocumented attribute."""
self.undocumented = UndocumentedNodes(function=0, klass=0, method=0, module=0)
def get_global_message_count(self, type_name: str) -> int:
- """Get a global message count"""
+ """Get a global message count."""
return getattr(self, type_name, 0)
def get_module_message_count(self, modname: str, type_name: str) -> int:
- """Get a module message count"""
+ """Get a module message count."""
return getattr(self.by_module[modname], type_name, 0)
def increase_single_message_count(self, type_name: str, increase: int) -> None:
- """Increase the message type count of an individual message type"""
+ """Increase the message type count of an individual message type."""
setattr(self, type_name, getattr(self, type_name) + increase)
def increase_single_module_message_count(
self, modname: str, type_name: MessageTypesFullName, increase: int
) -> None:
- """Increase the message type count of an individual message type of a module"""
+ """Increase the message type count of an individual message type of a module."""
self.by_module[modname][type_name] += increase
def reset_message_count(self) -> None:
- """Resets the message type count of the stats object"""
+ """Resets the message type count of the stats object."""
self.convention = 0
self.error = 0
self.fatal = 0
@@ -303,7 +303,7 @@ class LinterStats:
def merge_stats(stats: List[LinterStats]):
- """Used to merge multiple stats objects into a new one when pylint is run in parallel mode"""
+ """Used to merge multiple stats objects into a new one when pylint is run in parallel mode."""
merged = LinterStats()
for stat in stats:
merged.bad_names["argument"] += stat.bad_names["argument"]
diff --git a/pylint/utils/pragma_parser.py b/pylint/utils/pragma_parser.py
index 5ef4ef481..0bf25de7c 100644
--- a/pylint/utils/pragma_parser.py
+++ b/pylint/utils/pragma_parser.py
@@ -61,7 +61,7 @@ def emit_pragma_representer(action: str, messages: List[str]) -> PragmaRepresent
class PragmaParserError(Exception):
- """A class for exceptions thrown by pragma_parser module"""
+ """A class for exceptions thrown by pragma_parser module."""
def __init__(self, message: str, token: str) -> None:
""":args message: explain the reason why the exception has been thrown
@@ -73,11 +73,11 @@ class PragmaParserError(Exception):
class UnRecognizedOptionError(PragmaParserError):
- """Thrown in case the of a valid but unrecognized option"""
+ """Thrown in case the of a valid but unrecognized option."""
class InvalidPragmaError(PragmaParserError):
- """Thrown in case the pragma is invalid"""
+ """Thrown in case the pragma is invalid."""
def parse_pragma(pylint_pragma: str) -> Generator[PragmaRepresenter, None, None]:
diff --git a/pylint/utils/utils.py b/pylint/utils/utils.py
index f99690b33..c3d120458 100644
--- a/pylint/utils/utils.py
+++ b/pylint/utils/utils.py
@@ -98,7 +98,7 @@ def cmp(a, b):
def diff_string(old, new):
- """given an old and new int value, return a string representing the
+ """Given an old and new int value, return a string representing the
difference
"""
diff = abs(old - new)
@@ -107,7 +107,7 @@ def diff_string(old, new):
def get_module_and_frameid(node):
- """return the module name and the frame id in the module"""
+ """Return the module name and the frame id in the module."""
frame = node.frame(future=True)
module, obj = "", []
while frame:
@@ -129,7 +129,7 @@ def get_rst_title(title, character):
def get_rst_section(section, options, doc=None):
- """format an option's section using as a ReStructuredText formatted output"""
+ """Format an option's section using as a ReStructuredText formatted output."""
result = ""
if section:
result += get_rst_title(section, "'")
@@ -167,7 +167,7 @@ def tokenize_module(node: nodes.Module) -> List[tokenize.TokenInfo]:
def register_plugins(linter, directory):
- """load all module and package in the given directory, looking for a
+ """Load all module and package in the given directory, looking for a
'register' function in each one, used to register pylint checkers
"""
imported = {}
@@ -276,7 +276,7 @@ def get_global_option(
def _splitstrip(string, sep=","):
- """return a list of stripped string by splitting the string given as
+ """Return a list of stripped string by splitting the string given as
argument on `sep` (',' by default). Empty string are discarded.
>>> _splitstrip('a, b, c , 4,,')
@@ -299,7 +299,7 @@ def _splitstrip(string, sep=","):
def _unquote(string):
- """remove optional quotes (simple or double) from the string
+ """Remove optional quotes (simple or double) from the string.
:type string: str or unicode
:param string: an optionally quoted string
@@ -323,14 +323,14 @@ def _check_csv(value):
def _comment(string: str) -> str:
- """return string as a comment"""
+ """Return string as a comment."""
lines = [line.strip() for line in string.splitlines()]
sep = "\n"
return "# " + f"{sep}# ".join(lines)
def _format_option_value(optdict, value):
- """return the user input's value from a 'compiled' value"""
+ """Return the user input's value from a 'compiled' value."""
if optdict.get("type", None) == "py_version":
value = ".".join(str(item) for item in value)
elif isinstance(value, (list, tuple)):
@@ -350,7 +350,7 @@ def _format_option_value(optdict, value):
def format_section(
stream: TextIO, section: str, options: List[Tuple], doc: Optional[str] = None
) -> None:
- """Format an option's section using the INI format"""
+ """Format an option's section using the INI format."""
if doc:
print(_comment(doc), file=stream)
print(f"[{section}]", file=stream)
@@ -358,7 +358,7 @@ def format_section(
def _ini_format(stream: TextIO, options: List[Tuple]) -> None:
- """format options using the INI format"""
+ """Format options using the INI format."""
for optname, optdict, value in options:
value = _format_option_value(optdict, value)
help_opt = optdict.get("help")
diff --git a/script/fix_documentation.py b/script/fix_documentation.py
index 36fd931f0..0fc4e347e 100644
--- a/script/fix_documentation.py
+++ b/script/fix_documentation.py
@@ -23,7 +23,7 @@ def fix_inline_code_blocks(file_content: str) -> str:
def changelog_insert_empty_lines(file_content: str, subtitle_text: str) -> str:
- """Insert up to two empty lines before `What's New` entry in ChangeLog"""
+ """Insert up to two empty lines before `What's New` entry in ChangeLog."""
lines = file_content.split("\n")
subtitle_count = 0
for i, line in enumerate(lines):
diff --git a/script/get_unused_message_id_category.py b/script/get_unused_message_id_category.py
index 5ddcd0b3c..2741148c0 100644
--- a/script/get_unused_message_id_category.py
+++ b/script/get_unused_message_id_category.py
@@ -1,4 +1,4 @@
-"""Small script to get a new unused message id category"""
+"""Small script to get a new unused message id category."""
# 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
@@ -10,7 +10,7 @@ from pylint.lint.pylinter import PyLinter
def register_all_checkers_and_plugins(linter: "PyLinter") -> None:
- """Registers all checkers and plugins"""
+ """Registers all checkers and plugins."""
linter.cmdline_parser.set_conflict_handler("resolve")
initialize_checkers(linter)
initialize_extensions(linter)
diff --git a/tests/benchmark/test_baseline_benchmarks.py b/tests/benchmark/test_baseline_benchmarks.py
index 5227ca5ae..4865a3bd5 100644
--- a/tests/benchmark/test_baseline_benchmarks.py
+++ b/tests/benchmark/test_baseline_benchmarks.py
@@ -1,4 +1,4 @@
-""" Profiles basic -jX functionality """
+"""Profiles basic -jX functionality."""
# Copyright (c) 2020-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2020 Claudiu Popa <pcmanticore@gmail.com>
@@ -37,7 +37,7 @@ def _empty_filepath():
class SleepingChecker(BaseChecker):
- """A checker that sleeps, the wall-clock time should reduce as we add workers
+ """A checker that sleeps, the wall-clock time should reduce as we add workers.
As we apply a roughly constant amount of "work" in this checker any variance is
likely to be caused by the pylint system.
@@ -56,7 +56,7 @@ class SleepingChecker(BaseChecker):
sleep_duration = 0.5 # the time to pretend we're doing work for
def process_module(self, _node: nodes.Module) -> None:
- """Sleeps for `sleep_duration` on each call
+ """Sleeps for `sleep_duration` on each call.
This effectively means each file costs ~`sleep_duration`+framework overhead
"""
@@ -64,7 +64,7 @@ class SleepingChecker(BaseChecker):
class SleepingCheckerLong(BaseChecker):
- """A checker that sleeps, the wall-clock time should reduce as we add workers
+ """A checker that sleeps, the wall-clock time should reduce as we add workers.
As we apply a roughly constant amount of "work" in this checker any variance is
likely to be caused by the pylint system.
@@ -83,7 +83,7 @@ class SleepingCheckerLong(BaseChecker):
sleep_duration = 0.5 # the time to pretend we're doing work for
def process_module(self, _node: nodes.Module) -> None:
- """Sleeps for `sleep_duration` on each call
+ """Sleeps for `sleep_duration` on each call.
This effectively means each file costs ~`sleep_duration`+framework overhead
"""
@@ -91,7 +91,7 @@ class SleepingCheckerLong(BaseChecker):
class NoWorkChecker(BaseChecker):
- """A checker that sleeps, the wall-clock time should change as we add threads"""
+ """A checker that sleeps, the wall-clock time should change as we add threads."""
__implements__ = (pylint.interfaces.IRawChecker,)
@@ -112,7 +112,7 @@ class NoWorkChecker(BaseChecker):
group="baseline",
)
class TestEstablishBaselineBenchmarks:
- """Naive benchmarks for the high-level pylint framework
+ """Naive benchmarks for the high-level pylint framework.
Because this benchmarks the fundamental and common parts and changes seen here will
impact everything else
@@ -127,7 +127,7 @@ class TestEstablishBaselineBenchmarks:
lot_of_files = 500
def test_baseline_benchmark_j1(self, benchmark):
- """Establish a baseline of pylint performance with no work
+ """Establish a baseline of pylint performance with no work.
We will add extra Checkers in other benchmarks.
@@ -143,7 +143,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_benchmark_j10(self, benchmark):
- """Establish a baseline of pylint performance with no work across threads
+ """Establish a baseline of pylint performance with no work across threads.
Same as `test_baseline_benchmark_j1` but we use -j10 with 10 fake files to
ensure end-to-end-system invoked.
@@ -165,7 +165,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_benchmark_check_parallel_j10(self, benchmark):
- """Should demonstrate times very close to `test_baseline_benchmark_j10`"""
+ """Should demonstrate times very close to `test_baseline_benchmark_j10`."""
linter = PyLinter(reporter=Reporter())
# Create file per worker, using all workers
@@ -178,7 +178,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_lots_of_files_j1(self, benchmark):
- """Establish a baseline with only 'master' checker being run in -j1
+ """Establish a baseline with only 'master' checker being run in -j1.
We do not register any checkers except the default 'master', so the cost is just
that of the system with a lot of files registered
@@ -197,7 +197,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_lots_of_files_j10(self, benchmark):
- """Establish a baseline with only 'master' checker being run in -j10
+ """Establish a baseline with only 'master' checker being run in -j10.
As with the -j1 variant above `test_baseline_lots_of_files_j1`, we do not
register any checkers except the default 'master', so the cost is just that of
@@ -217,7 +217,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_lots_of_files_j1_empty_checker(self, benchmark):
- """Baselines pylint for a single extra checker being run in -j1, for N-files
+ """Baselines pylint for a single extra checker being run in -j1, for N-files.
We use a checker that does no work, so the cost is just that of the system at
scale
@@ -237,7 +237,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_lots_of_files_j10_empty_checker(self, benchmark):
- """Baselines pylint for a single extra checker being run in -j10, for N-files
+ """Baselines pylint for a single extra checker being run in -j10, for N-files.
We use a checker that does no work, so the cost is just that of the system at
scale, across workers
@@ -257,7 +257,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_benchmark_j1_single_working_checker(self, benchmark):
- """Establish a baseline of single-worker performance for PyLinter
+ """Establish a baseline of single-worker performance for PyLinter.
Here we mimic a single Checker that does some work so that we can see the
impact of running a simple system with -j1 against the same system with -j10.
@@ -283,7 +283,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_benchmark_j10_single_working_checker(self, benchmark):
- """Establishes baseline of multi-worker performance for PyLinter/check_parallel
+ """Establishes baseline of multi-worker performance for PyLinter/check_parallel.
We expect this benchmark to take less time that test_baseline_benchmark_j1,
`error_margin*(1/J)*(numfiles*SleepingChecker.sleep_duration)`
@@ -310,7 +310,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(linter.reporter.messages)}"
def test_baseline_benchmark_j1_all_checks_single_file(self, benchmark):
- """Runs a single file, with -j1, against all plug-ins
+ """Runs a single file, with -j1, against all plug-ins.
... that's the intent at least.
"""
@@ -327,7 +327,7 @@ class TestEstablishBaselineBenchmarks:
), f"Expected no errors to be thrown: {pprint.pformat(runner.linter.reporter.messages)}"
def test_baseline_benchmark_j1_all_checks_lots_of_files(self, benchmark):
- """Runs lots of files, with -j1, against all plug-ins
+ """Runs lots of files, with -j1, against all plug-ins.
... that's the intent at least.
"""
diff --git a/tests/checkers/unittest_design.py b/tests/checkers/unittest_design.py
index faf8f6e9e..b60106590 100644
--- a/tests/checkers/unittest_design.py
+++ b/tests/checkers/unittest_design.py
@@ -47,7 +47,7 @@ class TestDesignChecker(CheckerTestCase):
@set_config(exclude_too_few_public_methods="toml.*")
def test_exclude_too_few_methods_with_value(self) -> None:
- """Test exclude-too-few-public-methods option with value"""
+ """Test exclude-too-few-public-methods option with value."""
options = get_global_option(self.checker, "exclude-too-few-public-methods")
assert any(i.match("toml") for i in options)
diff --git a/tests/checkers/unittest_format.py b/tests/checkers/unittest_format.py
index 8aa7ec0c7..30972cb5c 100644
--- a/tests/checkers/unittest_format.py
+++ b/tests/checkers/unittest_format.py
@@ -26,7 +26,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
-"""Check format checker helper functions"""
+"""Check format checker helper functions."""
import os
import tempfile
@@ -120,7 +120,7 @@ class TestSuperfluousParentheses(CheckerTestCase):
self.checker.process_tokens(_tokenize_str(code))
def testPositiveSuperfluousParensWalrusOperatorIf(self) -> None:
- """Test positive superfluous parens cases with the walrus operator"""
+ """Test positive superfluous parens cases with the walrus operator."""
cases = [
(
MessageTest("superfluous-parens", line=1, args="if"),
@@ -162,7 +162,7 @@ class TestCheckSpace(CheckerTestCase):
CHECKER_CLASS = FormatChecker
def test_encoding_token(self) -> None:
- """Make sure the encoding token doesn't change the checker's behavior
+ """Make sure the encoding token doesn't change the checker's behavior.
_tokenize_str doesn't produce an encoding token, but
reading a file does
diff --git a/tests/checkers/unittest_non_ascii_name.py b/tests/checkers/unittest_non_ascii_name.py
index d0e3a85ab..4d69a6519 100644
--- a/tests/checkers/unittest_non_ascii_name.py
+++ b/tests/checkers/unittest_non_ascii_name.py
@@ -18,7 +18,7 @@ class TestNonAsciiChecker(pylint.testutils.CheckerTestCase):
sys.version_info < (3, 8), reason="requires python3.8 or higher"
)
def test_kwargs_and_position_only(self):
- """Even the new position only and keyword only should be found"""
+ """Even the new position only and keyword only should be found."""
node = astroid.extract_node(
"""
def name(
@@ -131,7 +131,7 @@ class TestNonAsciiChecker(pylint.testutils.CheckerTestCase):
code: str,
assign_type: str,
):
- """Variables defined no matter where, should be checked for non ascii"""
+ """Variables defined no matter where, should be checked for non ascii."""
assign_node = astroid.extract_node(code)
if not isinstance(assign_node, nodes.AssignName):
@@ -256,7 +256,7 @@ class TestNonAsciiChecker(pylint.testutils.CheckerTestCase):
],
)
def test_check_import(self, import_statement: str, wrong_name: Optional[str]):
- """We expect that for everything that user can change there is a message"""
+ """We expect that for everything that user can change there is a message."""
node = astroid.extract_node(f"{import_statement} #@")
expected_msgs: Iterable[pylint.testutils.MessageTest] = tuple()
diff --git a/tests/checkers/unittest_similar.py b/tests/checkers/unittest_similar.py
index 5caaac794..2f2b43115 100644
--- a/tests/checkers/unittest_similar.py
+++ b/tests/checkers/unittest_similar.py
@@ -394,7 +394,7 @@ def test_no_args() -> None:
def test_get_map_data() -> None:
- """Tests that a SimilarChecker respects the MapReduceMixin interface"""
+ """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))
diff --git a/tests/checkers/unittest_typecheck.py b/tests/checkers/unittest_typecheck.py
index cafb3b40f..4564a461e 100644
--- a/tests/checkers/unittest_typecheck.py
+++ b/tests/checkers/unittest_typecheck.py
@@ -46,7 +46,7 @@ needs_c_extension = pytest.mark.skipif(
class TestTypeChecker(CheckerTestCase):
- """Tests for pylint.checkers.typecheck"""
+ """Tests for pylint.checkers.typecheck."""
CHECKER_CLASS = typecheck.TypeChecker
diff --git a/tests/checkers/unittest_unicode/unittest_bad_chars.py b/tests/checkers/unittest_unicode/unittest_bad_chars.py
index 3605ac06d..1f1e1e8d9 100644
--- a/tests/checkers/unittest_unicode/unittest_bad_chars.py
+++ b/tests/checkers/unittest_unicode/unittest_bad_chars.py
@@ -16,7 +16,7 @@ from . import CODEC_AND_MSG, FakeNode
@pytest.fixture()
def bad_char_file_generator(tmp_path: Path) -> Callable[[str, bool, str], Path]:
- """generates a test file for bad chars
+ """Generates a test file for bad chars.
The generator also ensures that file generated is correct
"""
@@ -253,7 +253,7 @@ class TestBadCharsChecker(pylint.testutils.CheckerTestCase):
],
)
def test___check_invalid_chars(self, char: str, msg: str, codec: str) -> None:
- """Check function should deliver correct column no matter which codec we used"""
+ """Check function should deliver correct column no matter which codec we used."""
with self.assertAddsMessages(
pylint.testutils.MessageTest(
msg_id=msg,
diff --git a/tests/checkers/unittest_unicode/unittest_bidirectional_unicode.py b/tests/checkers/unittest_unicode/unittest_bidirectional_unicode.py
index c76db73ea..2416957c9 100644
--- a/tests/checkers/unittest_unicode/unittest_bidirectional_unicode.py
+++ b/tests/checkers/unittest_unicode/unittest_bidirectional_unicode.py
@@ -75,7 +75,7 @@ class TestBidirectionalUnicodeChecker(pylint.testutils.CheckerTestCase):
],
)
def test_find_bidi_string(self, bad_string: str, codec: str):
- """Ensure that all Bidirectional strings are detected
+ """Ensure that all Bidirectional strings are detected.
Tests also UTF-16 and UTF-32.
"""
diff --git a/tests/checkers/unittest_unicode/unittest_functions.py b/tests/checkers/unittest_unicode/unittest_functions.py
index a84c0be42..d14d2fdad 100644
--- a/tests/checkers/unittest_unicode/unittest_functions.py
+++ b/tests/checkers/unittest_unicode/unittest_functions.py
@@ -102,7 +102,7 @@ def test_map_positions_to_result(
expected: Dict[int, pylint.checkers.unicode._BadChar],
search_dict,
):
- """test all possible outcomes for map position function in UTF-8 and ASCII"""
+ """Test all possible outcomes for map position function in UTF-8 and ASCII."""
if isinstance(line, bytes):
newline = b"\n"
else:
@@ -212,7 +212,7 @@ def test__normalize_codec_name(codec: str, expected: str):
def test___fix_utf16_32_line_stream(
tmp_path: Path, codec: str, line_ending: str, final_new_line: bool
):
- """content of stream should be the same as should be the length"""
+ """Content of stream should be the same as should be the length."""
def decode_line(line: bytes, codec: str) -> str:
return line.decode(codec)
diff --git a/tests/checkers/unittest_unicode/unittest_invalid_encoding.py b/tests/checkers/unittest_unicode/unittest_invalid_encoding.py
index a2e58dc83..5facf9a05 100644
--- a/tests/checkers/unittest_unicode/unittest_invalid_encoding.py
+++ b/tests/checkers/unittest_unicode/unittest_invalid_encoding.py
@@ -121,11 +121,11 @@ class TestInvalidEncoding(pylint.testutils.CheckerTestCase):
],
)
def test__determine_codec(self, content: bytes, codec: str, line: int):
- """The codec determined should be exact no matter what we throw at it"""
+ """The codec determined should be exact no matter what we throw at it."""
assert self.checker._determine_codec(io.BytesIO(content)) == (codec, line)
def test__determine_codec_raises_syntax_error_on_invalid_input(self):
- """invalid input should lead to a SyntaxError"""
+ """Invalid input should lead to a SyntaxError."""
with pytest.raises(SyntaxError):
self.checker._determine_codec(io.BytesIO(b"\x80abc"))
diff --git a/tests/checkers/unittest_utils.py b/tests/checkers/unittest_utils.py
index 58ff5ed73..1b916b98a 100644
--- a/tests/checkers/unittest_utils.py
+++ b/tests/checkers/unittest_utils.py
@@ -489,7 +489,7 @@ def test_is_empty_literal() -> None:
def test_deprecation_is_inside_lambda() -> None:
- """Test that is_inside_lambda is throwing a DeprecationWarning"""
+ """Test that is_inside_lambda is throwing a DeprecationWarning."""
with pytest.warns(DeprecationWarning) as records:
utils.is_inside_lambda(nodes.NodeNG())
assert len(records) == 1
diff --git a/tests/config/file_to_lint.py b/tests/config/file_to_lint.py
index e7c395dd9..bc3f722d9 100644
--- a/tests/config/file_to_lint.py
+++ b/tests/config/file_to_lint.py
@@ -1 +1 @@
-"""Perfect module with only documentation for configuration tests"""
+"""Perfect module with only documentation for configuration tests."""
diff --git a/tests/config/unittest_config.py b/tests/config/unittest_config.py
index 72474abe3..fd56a3f92 100644
--- a/tests/config/unittest_config.py
+++ b/tests/config/unittest_config.py
@@ -89,7 +89,7 @@ class TestPyLinterOptionSetters(CheckerTestCase):
@set_config(ignore_paths=".*/tests/.*,.*\\ignore\\.*")
def test_ignore_paths_with_value(self) -> None:
- """Test ignore-paths option with value"""
+ """Test ignore-paths option with value."""
options = get_global_option(self.checker, "ignore-paths")
assert any(i.match("dir/tests/file.py") for i in options)
diff --git a/tests/conftest.py b/tests/conftest.py
index bdd3e4516..1f2347a1a 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -74,7 +74,7 @@ def pytest_addoption(parser) -> None:
def pytest_collection_modifyitems(config, items) -> None:
- """Convert command line options to markers"""
+ """Convert command line options to markers."""
# Add skip_primer_external mark
if not config.getoption("--primer-external"):
skip_primer_external = pytest.mark.skip(
diff --git a/tests/extensions/test_check_docs_utils.py b/tests/extensions/test_check_docs_utils.py
index b8851a1ff..2fa5719fd 100644
--- a/tests/extensions/test_check_docs_utils.py
+++ b/tests/extensions/test_check_docs_utils.py
@@ -24,7 +24,7 @@ from pylint.extensions import _check_docs_utils as utils
[("abc", 0), ("", 0), (" abc", 2), ("\n abc", 0), (" \n abc", 3)],
)
def test_space_indentation(string: str, count: int) -> None:
- """Test for pylint_plugin.ParamDocChecker"""
+ """Test for pylint_plugin.ParamDocChecker."""
assert utils.space_indentation(string) == count
diff --git a/tests/lint/unittest_expand_modules.py b/tests/lint/unittest_expand_modules.py
index 4d2cc812e..bb00a67ac 100644
--- a/tests/lint/unittest_expand_modules.py
+++ b/tests/lint/unittest_expand_modules.py
@@ -78,10 +78,10 @@ init_of_package = {
class TestExpandModules(CheckerTestCase):
- """Test the expand_modules function while allowing options to be set"""
+ """Test the expand_modules function while allowing options to be set."""
class Checker(BaseChecker):
- """This dummy checker is needed to allow options to be set"""
+ """This dummy checker is needed to allow options to be set."""
name = "checker"
msgs: Dict[str, Tuple[str, ...]] = {}
@@ -107,7 +107,7 @@ class TestExpandModules(CheckerTestCase):
)
@set_config(ignore_paths="")
def test_expand_modules(self, files_or_modules, expected):
- """Test expand_modules with the default value of ignore-paths"""
+ """Test expand_modules with the default value of ignore-paths."""
ignore_list, ignore_list_re = [], []
modules, errors = expand_modules(
files_or_modules,
@@ -133,7 +133,7 @@ class TestExpandModules(CheckerTestCase):
)
@set_config(ignore_paths=".*/lint/.*")
def test_expand_modules_with_ignore(self, files_or_modules, expected):
- """Test expand_modules with a non-default value of ignore-paths"""
+ """Test expand_modules with a non-default value of ignore-paths."""
ignore_list, ignore_list_re = [], []
modules, errors = expand_modules(
files_or_modules,
diff --git a/tests/lint/unittest_lint.py b/tests/lint/unittest_lint.py
index 6ac33b830..9dd6ae4de 100644
--- a/tests/lint/unittest_lint.py
+++ b/tests/lint/unittest_lint.py
@@ -386,7 +386,7 @@ def test_enable_message_block(initialized_linter: PyLinter) -> None:
def test_enable_by_symbol(initialized_linter: PyLinter) -> None:
- """messages can be controlled by symbolic names.
+ """Messages can be controlled by symbolic names.
The state is consistent across symbols and numbers.
"""
@@ -478,7 +478,7 @@ def test_disable_similar(initialized_linter: PyLinter) -> None:
def test_disable_alot(linter: PyLinter) -> None:
- """check that we disabled a lot of checkers"""
+ """Check that we disabled a lot of checkers."""
linter.set_option("reports", False)
linter.set_option("disable", "R,C,W")
checker_names = [c.name for c in linter.prepare_checkers()]
diff --git a/tests/message/unittest_message_id_store.py b/tests/message/unittest_message_id_store.py
index d1c140e9f..b44e33c6d 100644
--- a/tests/message/unittest_message_id_store.py
+++ b/tests/message/unittest_message_id_store.py
@@ -97,7 +97,7 @@ def test_duplicate_msgid(msgid_store: MessageIdStore) -> None:
def test_exclusivity_of_msgids() -> None:
- """Test to see if all checkers have an exclusive message id prefix"""
+ """Test to see if all checkers have an exclusive message id prefix."""
err_msg = (
"{} has the same prefix ('{}') as the '{}' checker. Please make sure the prefix "
"is unique for each checker. You can use 'script/get_unused_message_id_category.py' "
diff --git a/tests/primer/test_primer_external.py b/tests/primer/test_primer_external.py
index 12206b0fc..193eabf1d 100644
--- a/tests/primer/test_primer_external.py
+++ b/tests/primer/test_primer_external.py
@@ -30,7 +30,7 @@ PACKAGE_TO_LINT_JSON_BATCH_ONE = (
PACKAGES_TO_LINT_BATCH_ONE = get_packages_to_lint_from_json(
PACKAGE_TO_LINT_JSON_BATCH_ONE
)
-"""Dictionary of external packages used during the primer test in batch one"""
+"""Dictionary of external packages used during the primer test in batch one."""
PACKAGE_TO_LINT_JSON_BATCH_TWO = (
Path(__file__).parent / "packages_to_lint_batch_two.json"
@@ -38,7 +38,7 @@ PACKAGE_TO_LINT_JSON_BATCH_TWO = (
PACKAGES_TO_LINT_BATCH_TWO = get_packages_to_lint_from_json(
PACKAGE_TO_LINT_JSON_BATCH_TWO
)
-"""Dictionary of external packages used during the primer test in batch two"""
+"""Dictionary of external packages used during the primer test in batch two."""
class TestPrimer:
@@ -68,7 +68,7 @@ class TestPrimer:
@staticmethod
def _primer_test(package: PackageToLint, caplog: LogCaptureFixture) -> None:
- """Runs pylint over external packages to check for crashes and fatal messages
+ """Runs pylint over external packages to check for crashes and fatal messages.
We only check for crashes (bit-encoded exit code 32) and fatal messages
(bit-encoded exit code 1). We assume that these external repositories do not
diff --git a/tests/primer/test_primer_stdlib.py b/tests/primer/test_primer_stdlib.py
index 96c847bc8..824c1feac 100644
--- a/tests/primer/test_primer_stdlib.py
+++ b/tests/primer/test_primer_stdlib.py
@@ -46,7 +46,7 @@ MODULES_NAMES = [m[1] for m in MODULES_TO_CHECK]
def test_primer_stdlib_no_crash(
test_module_location: str, test_module_name: str, capsys: CaptureFixture
) -> None:
- """Test that pylint does not produce any crashes or fatal errors on stdlib modules"""
+ """Test that pylint does not produce any crashes or fatal errors on stdlib modules."""
__tracebackhide__ = True # pylint: disable=unused-variable
os.chdir(test_module_location)
with _patch_stdout(io.StringIO()):
diff --git a/tests/profile/test_profile_against_externals.py b/tests/profile/test_profile_against_externals.py
index 128a34738..7be4930e8 100644
--- a/tests/profile/test_profile_against_externals.py
+++ b/tests/profile/test_profile_against_externals.py
@@ -1,4 +1,4 @@
-""" Profiles basic -jX functionality """
+"""Profiles basic -jX functionality."""
# Copyright (c) 2020-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2020 Frank Harrison <frank@doublethefish.com>
# Copyright (c) 2021 Daniƫl van Noord <13665637+DanielNoord@users.noreply.github.com>
@@ -42,7 +42,7 @@ def _get_py_files(scanpath):
"name,git_repo", [("numpy", "https://github.com/numpy/numpy.git")]
)
def test_run(tmp_path, name, git_repo):
- """Runs pylint against external sources"""
+ """Runs pylint against external sources."""
checkoutdir = tmp_path / name
checkoutdir.mkdir()
os.system(f"git clone --depth=1 {git_repo} {checkoutdir}")
diff --git a/tests/pyreverse/conftest.py b/tests/pyreverse/conftest.py
index c83e74cbd..ed3ad8f42 100644
--- a/tests/pyreverse/conftest.py
+++ b/tests/pyreverse/conftest.py
@@ -62,7 +62,7 @@ def html_config() -> PyreverseConfig:
@pytest.fixture(scope="session")
def get_project() -> Callable:
def _get_project(module: str, name: Optional[str] = "No Name") -> Project:
- """return an astroid project representation"""
+ """Return an astroid project representation."""
def _astroid_wrapper(func: Callable, modname: str) -> Module:
return func(modname)
diff --git a/tests/pyreverse/test_diadefs.py b/tests/pyreverse/test_diadefs.py
index 5fe73bf36..d9a358936 100644
--- a/tests/pyreverse/test_diadefs.py
+++ b/tests/pyreverse/test_diadefs.py
@@ -21,7 +21,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
-"""Unit test for the extensions.diadefslib modules"""
+"""Unit test for the extensions.diadefslib modules."""
# pylint: disable=redefined-outer-name
import sys
from pathlib import Path
@@ -42,14 +42,14 @@ from pylint.testutils.pyreverse import PyreverseConfig
def _process_classes(classes: List[DiagramEntity]) -> List[Tuple[bool, str]]:
- """extract class names of a list"""
+ """Extract class names of a list."""
return sorted((isinstance(c.node, nodes.ClassDef), c.title) for c in classes)
def _process_relations(
relations: Dict[str, List[Relationship]]
) -> List[Tuple[str, str, str]]:
- """extract relation indices from a relation list"""
+ """Extract relation indices from a relation list."""
result = []
for rel_type, rels in relations.items():
for rel in rels:
@@ -71,7 +71,7 @@ def PROJECT(get_project):
def test_option_values(
default_config: PyreverseConfig, HANDLER: DiadefsHandler, PROJECT: Project
) -> None:
- """test for ancestor, associated and module options"""
+ """Test for ancestor, associated and module options."""
df_h = DiaDefGenerator(Linker(PROJECT), HANDLER)
cl_config = default_config
cl_config.classes = ["Specialization"]
@@ -102,7 +102,7 @@ def test_option_values(
def test_default_values() -> None:
- """test default values for package or class diagrams"""
+ """Test default values for package or class diagrams."""
# TODO : should test difference between default values for package or class diagrams pylint: disable=fixme
@@ -118,7 +118,7 @@ class TestDefaultDiadefGenerator:
def test_exctract_relations(
self, HANDLER: DiadefsHandler, PROJECT: Project
) -> None:
- """test extract_relations between classes"""
+ """Test extract_relations between classes."""
cd = DefaultDiadefGenerator(Linker(PROJECT), HANDLER).visit(PROJECT)[1]
cd.extract_relationships()
relations = _process_relations(cd.relationships)
@@ -127,7 +127,7 @@ class TestDefaultDiadefGenerator:
def test_functional_relation_extraction(
self, default_config: PyreverseConfig, get_project: Callable
) -> None:
- """functional test of relations extraction;
+ """Functional test of relations extraction;
different classes possibly in different modules
"""
# XXX should be catching pyreverse environment problem but doesn't
diff --git a/tests/pyreverse/test_diagrams.py b/tests/pyreverse/test_diagrams.py
index db8a4e645..b307a37d8 100644
--- a/tests/pyreverse/test_diagrams.py
+++ b/tests/pyreverse/test_diagrams.py
@@ -5,7 +5,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
-"""Unit test for the diagrams modules"""
+"""Unit test for the diagrams modules."""
from typing import Callable
from pylint.pyreverse.diadefslib import DefaultDiadefGenerator, DiadefsHandler
diff --git a/tests/pyreverse/test_inspector.py b/tests/pyreverse/test_inspector.py
index 6fff4e5fc..3a4ee423c 100644
--- a/tests/pyreverse/test_inspector.py
+++ b/tests/pyreverse/test_inspector.py
@@ -13,7 +13,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
-"""for the visitors.diadefs module"""
+"""For the visitors.diadefs module."""
# pylint: disable=redefined-outer-name
import os
diff --git a/tests/pyreverse/test_main.py b/tests/pyreverse/test_main.py
index 792bcbb8b..01f3ccc09 100644
--- a/tests/pyreverse/test_main.py
+++ b/tests/pyreverse/test_main.py
@@ -1,4 +1,4 @@
-"""Unittest for the main module"""
+"""Unittest for the main module."""
import os
import sys
from typing import Iterator
diff --git a/tests/pyreverse/test_printer_factory.py b/tests/pyreverse/test_printer_factory.py
index f39b90dad..73a5e2670 100644
--- a/tests/pyreverse/test_printer_factory.py
+++ b/tests/pyreverse/test_printer_factory.py
@@ -3,7 +3,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
-"""Unit tests for pylint.pyreverse.printer_factory"""
+"""Unit tests for pylint.pyreverse.printer_factory."""
import pytest
diff --git a/tests/pyreverse/test_utils.py b/tests/pyreverse/test_utils.py
index c79d43b77..f571b1847 100644
--- a/tests/pyreverse/test_utils.py
+++ b/tests/pyreverse/test_utils.py
@@ -8,7 +8,7 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/LICENSE
-"""Tests for pylint.pyreverse.utils"""
+"""Tests for pylint.pyreverse.utils."""
from typing import Any
from unittest.mock import patch
@@ -48,7 +48,7 @@ def test_get_visibility(names, expected):
],
)
def test_get_annotation_annassign(assign, label):
- """AnnAssign"""
+ """AnnAssign."""
node = astroid.extract_node(assign)
got = get_annotation(node.value).name
assert isinstance(node, nodes.AnnAssign)
@@ -67,7 +67,7 @@ def test_get_annotation_annassign(assign, label):
],
)
def test_get_annotation_assignattr(init_method, label):
- """AssignAttr"""
+ """AssignAttr."""
assign = rf"""
class A:
{init_method}
diff --git a/tests/pyreverse/test_writer.py b/tests/pyreverse/test_writer.py
index 426cef68e..122618213 100644
--- a/tests/pyreverse/test_writer.py
+++ b/tests/pyreverse/test_writer.py
@@ -17,7 +17,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
-"""Unit test for ``DiagramWriter``"""
+"""Unit test for ``DiagramWriter``."""
import codecs
@@ -61,7 +61,7 @@ HTML_FILES = ["packages_No_Name.html", "classes_No_Name.html"]
class Config:
- """config object for tests"""
+ """Config object for tests."""
def __init__(self):
for attr, value in _DEFAULTS.items():
diff --git a/tests/test_check_parallel.py b/tests/test_check_parallel.py
index bb6e150a3..f4ddef985 100644
--- a/tests/test_check_parallel.py
+++ b/tests/test_check_parallel.py
@@ -1,4 +1,4 @@
-"""Puts the check_parallel system under test"""
+"""Puts the check_parallel system under test."""
# Copyright (c) 2020-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2020 Frank Harrison <frank@doublethefish.com>
# Copyright (c) 2021 Jaehoon Hwang <jaehoonhwang@users.noreply.github.com>
@@ -34,7 +34,7 @@ from pylint.utils import LinterStats, ModuleStats
def _gen_file_data(idx: int = 0) -> FileItem:
- """Generates a file to use as a stream"""
+ """Generates a file to use as a stream."""
filepath = os.path.abspath(
os.path.join(os.path.dirname(__file__), "input", "similar1")
)
@@ -51,7 +51,7 @@ def _gen_file_datas(count: int = 1) -> List[FileItem]:
class SequentialTestChecker(BaseChecker):
- """A checker that does not need to consolidate data across run invocations"""
+ """A checker that does not need to consolidate data across run invocations."""
__implements__ = (pylint.interfaces.IRawChecker,)
@@ -71,7 +71,7 @@ class SequentialTestChecker(BaseChecker):
self.linter = linter
def process_module(self, _node: nodes.Module) -> None:
- """Called once per stream/file/astroid object"""
+ """Called once per stream/file/astroid object."""
# record the number of invocations with the data object
record = self.test_data + str(len(self.data))
self.data.append(record)
@@ -110,7 +110,7 @@ class ParallelTestChecker(BaseChecker, MapReduceMixin):
self.linter = linter
def open(self) -> None:
- """init the checkers: reset statistics information"""
+ """Init the checkers: reset statistics information."""
self.linter.stats.reset_node_count()
self.data = []
@@ -132,42 +132,42 @@ class ParallelTestChecker(BaseChecker, MapReduceMixin):
recombined.close()
def process_module(self, _node: nodes.Module) -> None:
- """Called once per stream/file/astroid object"""
+ """Called once per stream/file/astroid object."""
# record the number of invocations with the data object
record = self.test_data + str(len(self.data))
self.data.append(record)
class ExtraSequentialTestChecker(SequentialTestChecker):
- """A checker that does not need to consolidate data across run invocations"""
+ """A checker that does not need to consolidate data across run invocations."""
name = "extra-sequential-checker"
test_data = "extra-sequential"
class ExtraParallelTestChecker(ParallelTestChecker):
- """A checker that does need to consolidate data across run invocations"""
+ """A checker that does need to consolidate data across run invocations."""
name = "extra-parallel-checker"
test_data = "extra-parallel"
class ThirdSequentialTestChecker(SequentialTestChecker):
- """A checker that does not need to consolidate data across run invocations"""
+ """A checker that does not need to consolidate data across run invocations."""
name = "third-sequential-checker"
test_data = "third-sequential"
class ThirdParallelTestChecker(ParallelTestChecker):
- """A checker that does need to consolidate data across run invocations"""
+ """A checker that does need to consolidate data across run invocations."""
name = "third-parallel-checker"
test_data = "third-parallel"
class TestCheckParallelFramework:
- """Tests the check_parallel() function's framework"""
+ """Tests the check_parallel() function's framework."""
def setup_class(self):
self._prev_global_linter = pylint.lint.parallel._worker_linter
@@ -240,7 +240,7 @@ class TestCheckParallelFramework:
assert stats.warning == 0
def test_worker_check_sequential_checker(self) -> None:
- """Same as test_worker_check_single_file_no_checkers with SequentialTestChecker"""
+ """Same as test_worker_check_single_file_no_checkers with SequentialTestChecker."""
linter = PyLinter(reporter=Reporter())
worker_initialize(linter=dill.dumps(linter))
@@ -285,10 +285,10 @@ class TestCheckParallelFramework:
class TestCheckParallel:
- """Tests the check_parallel() function"""
+ """Tests the check_parallel() function."""
def test_sequential_checkers_work(self) -> None:
- """Tests original basic types of checker works as expected in -jN
+ """Tests original basic types of checker works as expected in -jN.
This means that a sequential checker should return the same data for a given
file-stream irrespective of whether it's run in -j1 or -jN
@@ -359,7 +359,7 @@ class TestCheckParallel:
assert linter.stats.warning == 0
def test_invoke_single_job(self) -> None:
- """Tests basic checkers functionality using just a single workderdo
+ """Tests basic checkers functionality using just a single workderdo.
This is *not* the same -j1 and does not happen under normal operation
"""
@@ -425,7 +425,7 @@ class TestCheckParallel:
],
)
def test_compare_workers_to_single_proc(self, num_files, num_jobs, num_checkers):
- """Compares the 3 key parameters for check_parallel() produces the same results
+ """Compares the 3 key parameters for check_parallel() produces the same results.
The intent here is to ensure that the check_parallel() operates on each file,
without ordering issues, irrespective of the number of workers used and the
@@ -525,7 +525,7 @@ class TestCheckParallel:
],
)
def test_map_reduce(self, num_files, num_jobs, num_checkers):
- """Compares the 3 key parameters for check_parallel() produces the same results
+ """Compares the 3 key parameters for check_parallel() produces the same results.
The intent here is to validate the reduce step: no stats should be lost.
diff --git a/tests/test_epylint.py b/tests/test_epylint.py
index 4f2d2aad0..8e7ff9b79 100644
--- a/tests/test_epylint.py
+++ b/tests/test_epylint.py
@@ -1,4 +1,4 @@
-"""Test for issue https://github.com/PyCQA/pylint/issues/4286"""
+"""Test for issue https://github.com/PyCQA/pylint/issues/4286."""
# pylint: disable=redefined-outer-name
from pathlib import PosixPath
diff --git a/tests/test_func.py b/tests/test_func.py
index 3e6bf36ce..492797ec2 100644
--- a/tests/test_func.py
+++ b/tests/test_func.py
@@ -18,7 +18,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
-"""functional/non regression tests for pylint"""
+"""Functional/non regression tests for pylint."""
import re
import sys
@@ -38,7 +38,7 @@ INFO_TEST_RGX = re.compile(r"^func_i\d\d\d\d$")
def exception_str(self, ex) -> str: # pylint: disable=unused-argument
- """function used to replace default __str__ method of exception instances
+ """Function used to replace default __str__ method of exception instances
This function is not typed because it is legacy code
"""
return f"in {ex.file}\n:: {', '.join(ex.args)}"
diff --git a/tests/test_import_graph.py b/tests/test_import_graph.py
index 6035601bf..9a4ea59a6 100644
--- a/tests/test_import_graph.py
+++ b/tests/test_import_graph.py
@@ -47,7 +47,7 @@ POSSIBLE_DOT_FILENAMES = ["foo.dot", "foo.gv", "tests/regrtest_data/foo.dot"]
@pytest.mark.parametrize("dest", POSSIBLE_DOT_FILENAMES, indirect=True)
def test_dependencies_graph(dest: str) -> None:
- """DOC files are correctly generated, and the graphname is the basename"""
+ """DOC files are correctly generated, and the graphname is the basename."""
imports._dependencies_graph(dest, {"labas": {"hoho", "yep"}, "hoho": {"yep"}})
with open(dest, encoding="utf-8") as stream:
assert (
@@ -73,7 +73,7 @@ URL="." node[shape="box"]
any(shutil.which(x) for x in ("dot", "gv")), reason="dot or gv is installed"
)
def test_missing_graphviz(filename: str) -> None:
- """Raises if graphviz is not installed, and defaults to png if no extension given"""
+ """Raises if graphviz is not installed, and defaults to png if no extension given."""
with pytest.raises(RuntimeError, match=r"Cannot generate `graph\.png`.*"):
imports._dependencies_graph(filename, {"a": {"b", "c"}, "b": {"c"}})
diff --git a/tests/test_pylint_runners.py b/tests/test_pylint_runners.py
index 88113cb2c..e4b20c0a8 100644
--- a/tests/test_pylint_runners.py
+++ b/tests/test_pylint_runners.py
@@ -27,7 +27,7 @@ def test_runner(runner: Callable, tmpdir: LocalPath) -> None:
"runner", [run_epylint, run_pylint, run_pyreverse, run_symilar]
)
def test_runner_with_arguments(runner: Callable, tmpdir: LocalPath) -> None:
- """Check the runners with arguments as parameter instead of sys.argv"""
+ """Check the runners with arguments as parameter instead of sys.argv."""
filepath = os.path.abspath(__file__)
testargs = [filepath]
with tmpdir.as_cwd():
diff --git a/tests/test_regr.py b/tests/test_regr.py
index 99b600275..3ece9c987 100644
--- a/tests/test_regr.py
+++ b/tests/test_regr.py
@@ -17,7 +17,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
-"""non regression tests for pylint, which requires a too specific configuration
+"""Non regression tests for pylint, which requires a too specific configuration
to be incorporated in the automatic functional test framework
"""
# pylint: disable=redefined-outer-name
diff --git a/tests/test_self.py b/tests/test_self.py
index 8b41654d2..61aa35d32 100644
--- a/tests/test_self.py
+++ b/tests/test_self.py
@@ -292,7 +292,7 @@ class TestRunTC:
self._runtest([], code=32)
def test_no_out_encoding(self) -> None:
- """test redirection of stdout with non ascii characters"""
+ """Test redirection of stdout with non ascii characters."""
# This test reproduces bug #48066 ; it happens when stdout is redirected
# through '>' : the sys.stdout.encoding becomes then None, and if the
# output contains non ascii, pylint will crash
@@ -1264,7 +1264,7 @@ class TestRunTC:
@staticmethod
def test_enable_all_extensions() -> None:
- """Test to see if --enable-all-extensions does indeed load all extensions"""
+ """Test to see if --enable-all-extensions does indeed load all extensions."""
# Record all extensions
plugins = []
for filename in os.listdir(os.path.dirname(extensions.__file__)):
@@ -1280,7 +1280,7 @@ class TestRunTC:
@staticmethod
def test_load_text_repoter_if_not_provided() -> None:
- """Test if PyLinter.reporter is a TextReporter if no reporter is provided"""
+ """Test if PyLinter.reporter is a TextReporter if no reporter is provided."""
linter = PyLinter()
assert isinstance(linter.reporter, TextReporter)
diff --git a/tests/testutils/test_decorator.py b/tests/testutils/test_decorator.py
index 0bd1fb119..4ab9d04f0 100644
--- a/tests/testutils/test_decorator.py
+++ b/tests/testutils/test_decorator.py
@@ -8,7 +8,7 @@ from pylint.testutils.decorator import set_config_directly
def test_deprecation_of_set_config_directly() -> None:
- """Test that the deprecation of set_config_directly works as expected"""
+ """Test that the deprecation of set_config_directly works as expected."""
with pytest.warns(DeprecationWarning) as records:
set_config_directly()
diff --git a/tests/unittest_reporters_json.py b/tests/unittest_reporters_json.py
index a1b76fe10..be7aadaba 100644
--- a/tests/unittest_reporters_json.py
+++ b/tests/unittest_reporters_json.py
@@ -28,7 +28,7 @@ expected_score_message = "Expected score message"
def test_simple_json_output_no_score() -> None:
- """Test JSON reporter with no score"""
+ """Test JSON reporter with no score."""
message = {
"msg": "line-too-long",
"line": 1,
@@ -57,7 +57,7 @@ def test_simple_json_output_no_score() -> None:
def test_simple_json_output_no_score_with_end_line() -> None:
- """Test JSON reporter with no score with end_line and end_column"""
+ """Test JSON reporter with no score with end_line and end_column."""
message = {
"msg": "line-too-long",
"line": 1,
diff --git a/tests/unittest_reporting.py b/tests/unittest_reporting.py
index 1ee947759..d6cb18220 100644
--- a/tests/unittest_reporting.py
+++ b/tests/unittest_reporting.py
@@ -58,7 +58,7 @@ def test_template_option(linter):
def test_template_option_default(linter) -> None:
- """Test the default msg-template setting"""
+ """Test the default msg-template setting."""
output = StringIO()
linter.reporter.out = output
linter.open()
@@ -72,7 +72,7 @@ def test_template_option_default(linter) -> None:
def test_template_option_end_line(linter) -> None:
- """Test the msg-template option with end_line and end_column"""
+ """Test the msg-template option with end_line and end_column."""
output = StringIO()
linter.reporter.out = output
linter.set_option(
@@ -125,7 +125,7 @@ def test_template_option_non_existing(linter) -> None:
def test_deprecation_set_output(recwarn):
- """TODO remove in 3.0"""
+ """TODO remove in 3.0."""
reporter = BaseReporter()
# noinspection PyDeprecation
reporter.set_output(sys.stdout)
diff --git a/tests/utils/unittest_utils.py b/tests/utils/unittest_utils.py
index 6514de872..485756e7d 100644
--- a/tests/utils/unittest_utils.py
+++ b/tests/utils/unittest_utils.py
@@ -25,7 +25,7 @@ from pylint.utils import utils
def test_decoding_stream_unknown_encoding() -> None:
- """decoding_stream should fall back to *some* decoding when given an
+ """Decoding_stream should fall back to *some* decoding when given an
unknown encoding.
"""
binary_io = io.BytesIO(b"foo\nbar")