diff options
36 files changed, 218 insertions, 256 deletions
diff --git a/pylint/checkers/base.py b/pylint/checkers/base.py index d830a68ba..17400bc11 100644 --- a/pylint/checkers/base.py +++ b/pylint/checkers/base.py @@ -210,7 +210,7 @@ TYPING_FORWARD_REF_QNAME = "typing.ForwardRef" def _redefines_import(node): - """ Detect that the given node (AssignName) is inside an + """Detect that the given node (AssignName) is inside an exception handler and redefines an import from the tryexcept body. Returns True if the node redefines an import, False otherwise. """ @@ -774,7 +774,7 @@ class BasicErrorChecker(_BasicChecker): @utils.check_messages("abstract-class-instantiated") def visit_call(self, node): - """ Check instantiating abstract class with + """Check instantiating abstract class with abc.ABCMeta as metaclass. """ try: @@ -1082,8 +1082,7 @@ class BasicChecker(_BasicChecker): self._tryfinallys = None def open(self): - """initialize visit variables and statistics - """ + """initialize visit variables and statistics""" self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0) @@ -1155,8 +1154,7 @@ class BasicChecker(_BasicChecker): self.add_message("using-constant-test", node=node) def visit_module(self, _): - """check module name, docstring and required arguments - """ + """check module name, docstring and required arguments""" self.stats["module"] += 1 def visit_classdef(self, node): # pylint: disable=unused-argument @@ -1246,8 +1244,7 @@ class BasicChecker(_BasicChecker): @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node): - """check whether or not the lambda is suspicious - """ + """check whether or not 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. diff --git a/pylint/checkers/base_checker.py b/pylint/checkers/base_checker.py index b1f6fe25b..ccdca6568 100644 --- a/pylint/checkers/base_checker.py +++ b/pylint/checkers/base_checker.py @@ -118,7 +118,7 @@ class BaseChecker(OptionsProviderMixIn): checker. :raises InvalidMessageError: If the checker id in the messages are not - always the same. """ + always the same.""" checker_id = None existing_ids = [] for message in self.messages: diff --git a/pylint/checkers/classes.py b/pylint/checkers/classes.py index df9c8e6aa..686bf278f 100644 --- a/pylint/checkers/classes.py +++ b/pylint/checkers/classes.py @@ -362,7 +362,7 @@ def _has_data_descriptor(cls, attr): def _called_in_methods(func, klass, methods): - """ Check if the func was called in any of the given methods, + """Check if the func was called in any of the given methods, belonging to the *klass*. Returns True if so, False otherwise. """ if not isinstance(func, astroid.FunctionDef): @@ -785,8 +785,7 @@ a metaclass class method.", "duplicate-bases", ) def visit_classdef(self, node): - """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): @@ -1265,7 +1264,7 @@ a metaclass class method.", self._check_in_slots(node) def _check_in_slots(self, node): - """ Check that the given AssignAttr node + """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) @@ -1681,8 +1680,7 @@ a metaclass class method.", self.add_message("super-init-not-called", args=klass.name, node=node) 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, astroid.FunctionDef) and isinstance(refmethod, astroid.FunctionDef) diff --git a/pylint/checkers/design_analysis.py b/pylint/checkers/design_analysis.py index 8e3fe064d..62905bc4a 100644 --- a/pylint/checkers/design_analysis.py +++ b/pylint/checkers/design_analysis.py @@ -294,8 +294,7 @@ class MisdesignChecker(BaseChecker): "too-many-public-methods", ) def visit_classdef(self, node): - """check size of inheritance hierarchy and number of instance attributes - """ + """check size of inheritance hierarchy and number of instance attributes""" nb_parents = len(list(node.ancestors())) if nb_parents > self.config.max_parents: self.add_message( diff --git a/pylint/checkers/format.py b/pylint/checkers/format.py index 13e6f7ada..fdbc8f4bc 100644 --- a/pylint/checkers/format.py +++ b/pylint/checkers/format.py @@ -452,9 +452,9 @@ class FormatChecker(BaseTokenChecker): def process_tokens(self, tokens): """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 - regular expression). + _ too long lines (i.e. longer than <max_chars>) + _ optionally bad construct (if given, bad_construct must be a compiled + regular expression). """ self._bracket_stack = [None] indents = [0] @@ -742,8 +742,7 @@ class FormatChecker(BaseTokenChecker): lineno += 1 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 a39c9ebbe..ccd884063 100644 --- a/pylint/checkers/imports.py +++ b/pylint/checkers/imports.py @@ -94,8 +94,7 @@ def _get_import_name(importnode, 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 = "%s.%s" % (base, name) if base else name first = None @@ -177,8 +176,7 @@ def _repr_tree_defs(data, indent_str=None): def _dependencies_graph(filename, dep_info): - """write dependencies as a dot (graphviz) file - """ + """write dependencies as a dot (graphviz) file""" done = {} printer = DotBackend(filename[:-4], rankdir="LR") printer.emit('URL="." node[shape="box"]') @@ -958,8 +956,7 @@ class ImportsChecker(BaseChecker): ) def _check_toplevel(self, node): - """Check whether the import is made outside the module toplevel. - """ + """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), astroid.Module): diff --git a/pylint/checkers/logging.py b/pylint/checkers/logging.py index c448cf476..6117b0f04 100644 --- a/pylint/checkers/logging.py +++ b/pylint/checkers/logging.py @@ -257,7 +257,9 @@ class LoggingChecker(checkers.BaseChecker): emit = total_number_of_strings > 0 if emit: self.add_message( - "logging-not-lazy", node=node, args=(self._helper_string(node),), + "logging-not-lazy", + node=node, + args=(self._helper_string(node),), ) elif isinstance(node.args[format_pos], astroid.Call): self._check_call_func(node.args[format_pos]) diff --git a/pylint/checkers/python3.py b/pylint/checkers/python3.py index 4e60873a0..0b9369a4a 100644 --- a/pylint/checkers/python3.py +++ b/pylint/checkers/python3.py @@ -163,8 +163,7 @@ def _in_iterating_context(node): def _is_conditional_import(node): - """Checks if an import node is in the context of a conditional. - """ + """Checks if an import node is in the context of a conditional.""" parent = node.parent return isinstance( parent, (astroid.TryExcept, astroid.ExceptHandler, astroid.If, astroid.IfExp) diff --git a/pylint/checkers/raw_metrics.py b/pylint/checkers/raw_metrics.py index 8fed7b614..c14f85c5b 100644 --- a/pylint/checkers/raw_metrics.py +++ b/pylint/checkers/raw_metrics.py @@ -29,8 +29,7 @@ from pylint.reporters.ureports.nodes import Table def report_raw_stats(sect, stats, _): - """calculate percentage of code / doc / comment / empty - """ + """calculate percentage of code / doc / comment / empty""" total_lines = stats["total_lines"] if not total_lines: raise EmptyReportError() diff --git a/pylint/checkers/refactoring/refactoring_checker.py b/pylint/checkers/refactoring/refactoring_checker.py index 4ba97f3b0..a296b7d40 100644 --- a/pylint/checkers/refactoring/refactoring_checker.py +++ b/pylint/checkers/refactoring/refactoring_checker.py @@ -768,8 +768,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(), astroid.FunctionDef): return diff --git a/pylint/checkers/spelling.py b/pylint/checkers/spelling.py index ff6d04620..5ac5e7b8d 100644 --- a/pylint/checkers/spelling.py +++ b/pylint/checkers/spelling.py @@ -65,8 +65,7 @@ else: class WordsWithDigigtsFilter(Filter): - """Skips words with digits. - """ + """Skips words with digits.""" def _skip(self, word): for char in word: diff --git a/pylint/checkers/stdlib.py b/pylint/checkers/stdlib.py index 06a700c1c..e0ee4f143 100644 --- a/pylint/checkers/stdlib.py +++ b/pylint/checkers/stdlib.py @@ -375,7 +375,7 @@ class StdlibChecker(BaseChecker): ) def _check_datetime(self, node): - """ Check that a datetime was inferred. + """Check that a datetime was inferred. If so, emit boolean-datetime warning. """ try: diff --git a/pylint/checkers/strings.py b/pylint/checkers/strings.py index 28f6083e5..e2e6557a9 100644 --- a/pylint/checkers/strings.py +++ b/pylint/checkers/strings.py @@ -220,7 +220,7 @@ BUILTINS_INT = builtins.__name__ + ".int" def get_access_path(key, parts): - """ Given a list of format specifiers, returns + """Given a list of format specifiers, returns the final access path (e.g. a.b.c[0][1]). """ path = [] @@ -388,10 +388,14 @@ class StringFormatChecker(BaseChecker): if not arg: continue arg_type = utils.safe_infer(arg) - if arg_type not in ( - None, - astroid.Uninferable, - ) and not arg_matches_format_type(arg_type, format_type): + if ( + arg_type + not in ( + None, + astroid.Uninferable, + ) + and not arg_matches_format_type(arg_type, format_type) + ): self.add_message( "bad-string-format-type", node=node, diff --git a/pylint/checkers/typecheck.py b/pylint/checkers/typecheck.py index d28516be8..0e669ec33 100644 --- a/pylint/checkers/typecheck.py +++ b/pylint/checkers/typecheck.py @@ -707,8 +707,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,) diff --git a/pylint/checkers/utils.py b/pylint/checkers/utils.py index d61418615..f3d23615e 100644 --- a/pylint/checkers/utils.py +++ b/pylint/checkers/utils.py @@ -272,8 +272,7 @@ def clobber_in_except( def is_super(node: astroid.node_classes.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_NAME: return True return False @@ -294,8 +293,7 @@ def is_builtin_object(node: astroid.node_classes.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 @@ -423,8 +421,7 @@ def is_ancestor_name( def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.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, (astroid.AssignName, astroid.Tuple, astroid.List)): node = node.parent return node @@ -544,7 +541,7 @@ def split_format_field_names(format_string) -> Tuple[str, Iterable[Tuple[bool, s def collect_string_fields(format_string) -> Iterable[Optional[str]]: - """ Given a format string, return an iterator + """Given a format string, return an iterator of all the valid format fields. It handles nested fields as well. """ diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index aa0af51b1..b42f229c7 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -187,7 +187,7 @@ def _get_unpacking_extra_info(node, inferred): def _detect_global_scope(node, frame, defframe): - """ Detect that the given frames shares a global + """Detect that the given frames shares a global scope. Two frames shares a global scope when neither @@ -258,7 +258,7 @@ def _infer_name_module(node, name): def _fix_dot_imports(not_consumed): - """ Try to fix imports with multiple dots, by returning a dictionary + """Try to fix imports with multiple dots, by returning a dictionary with the import names expanded. The function unflattens root imports, like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree' and 'xml.sax' respectively. @@ -739,8 +739,7 @@ class VariablesChecker(BaseChecker): "unused-variable", ) def leave_module(self, node): - """leave module: check globals - """ + """leave module: check globals""" assert len(self._to_consume) == 1 self._check_metaclasses(node) @@ -759,63 +758,52 @@ class VariablesChecker(BaseChecker): self._check_imports(not_consumed) def visit_classdef(self, node): - """visit class: update consumption analysis variable - """ + """visit class: update consumption analysis variable""" self._to_consume.append(NamesConsumer(node, "class")) def leave_classdef(self, _): - """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): - """visit lambda: update consumption analysis variable - """ + """visit lambda: update consumption analysis variable""" self._to_consume.append(NamesConsumer(node, "lambda")) def leave_lambda(self, _): - """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): - """visit genexpr: update consumption analysis variable - """ + """visit genexpr: update consumption analysis variable""" self._to_consume.append(NamesConsumer(node, "comprehension")) def leave_generatorexp(self, _): - """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): - """visit dictcomp: update consumption analysis variable - """ + """visit dictcomp: update consumption analysis variable""" self._to_consume.append(NamesConsumer(node, "comprehension")) def leave_dictcomp(self, _): - """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): - """visit setcomp: update consumption analysis variable - """ + """visit setcomp: update consumption analysis variable""" self._to_consume.append(NamesConsumer(node, "comprehension")) def leave_setcomp(self, _): - """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): - """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") @@ -1233,13 +1221,11 @@ class VariablesChecker(BaseChecker): # listcomp have now also their scope def visit_listcomp(self, node): - """visit dictcomp: update consumption analysis variable - """ + """visit dictcomp: update consumption analysis variable""" self._to_consume.append(NamesConsumer(node, "comprehension")) def leave_listcomp(self, _): - """leave dictcomp: update consumption analysis variable - """ + """leave dictcomp: update consumption analysis variable""" # do not check for not used locals here self._to_consume.pop() @@ -1830,7 +1816,7 @@ class VariablesChecker(BaseChecker): self.add_message("self-cls-assignment", node=node, args=(self_cls_name,)) def _check_unpacking(self, inferred, node, targets): - """ Check for unbalanced tuple unpacking + """Check for unbalanced tuple unpacking and unpacking non sequences. """ if utils.is_inside_abstract_class(node): diff --git a/pylint/config/__init__.py b/pylint/config/__init__.py index 8626135c7..56d23ba9f 100644 --- a/pylint/config/__init__.py +++ b/pylint/config/__init__.py @@ -91,8 +91,7 @@ def save_results(results, base): def find_pylintrc(): - """search the pylint rc file and return its path if it find it, else None - """ + """search the pylint rc file and return its path if it find it, else None""" for config_file in find_default_config_files(): if config_file.endswith("pylintrc"): return config_file diff --git a/pylint/extensions/check_elif.py b/pylint/extensions/check_elif.py index 220b6b833..6889261bd 100644 --- a/pylint/extensions/check_elif.py +++ b/pylint/extensions/check_elif.py @@ -17,8 +17,7 @@ from pylint.interfaces import IAstroidChecker, ITokenChecker 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" diff --git a/pylint/interfaces.py b/pylint/interfaces.py index 305e001ee..6503153a9 100644 --- a/pylint/interfaces.py +++ b/pylint/interfaces.py @@ -62,11 +62,10 @@ class IChecker(Interface): 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, astroid): - """ process a module + """process a module the module's content is accessible via astroid.stream """ @@ -83,21 +82,19 @@ 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): """Handle the given message object.""" def display_reports(self, layout): - """display results encapsulated in the layout tree - """ + """display results encapsulated in the layout tree""" __all__ = ("IRawChecker", "IAstroidChecker", "ITokenChecker", "IReporter") diff --git a/pylint/lint/pylinter.py b/pylint/lint/pylinter.py index 806007a21..1ce84a523 100644 --- a/pylint/lint/pylinter.py +++ b/pylint/lint/pylinter.py @@ -955,8 +955,7 @@ class PyLinter( yield (name, filepath, descr["basename"]) def _expand_files(self, modules): - """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 = utils.expand_modules( modules, self.config.black_list, self.config.black_list_re ) diff --git a/pylint/lint/run.py b/pylint/lint/run.py index 098ca41a6..35bc802b2 100644 --- a/pylint/lint/run.py +++ b/pylint/lint/run.py @@ -72,7 +72,11 @@ group are mutually exclusive.", return 1 def __init__( - self, args, reporter=None, exit=True, do_exit=UNUSED_PARAM_SENTINEL, + self, + args, + reporter=None, + exit=True, + do_exit=UNUSED_PARAM_SENTINEL, ): # pylint: disable=redefined-builtin self._rcfile = None self._version_asked = False diff --git a/pylint/pyreverse/diadefslib.py b/pylint/pyreverse/diadefslib.py index 8d9140829..1bb54a359 100644 --- a/pylint/pyreverse/diadefslib.py +++ b/pylint/pyreverse/diadefslib.py @@ -171,8 +171,7 @@ class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator): self.extract_classes(node, anc_level, association_level) def visit_importfrom(self, node): - """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) diff --git a/pylint/pyreverse/diagrams.py b/pylint/pyreverse/diagrams.py index 8c5eb485d..aae46fd6e 100644 --- a/pylint/pyreverse/diagrams.py +++ b/pylint/pyreverse/diagrams.py @@ -23,8 +23,7 @@ class Figure: class Relationship(Figure): - """a relation ship from an object in the diagram to another - """ + """a relation ship from an object in the diagram to another""" def __init__(self, from_object, to_object, relation_type, name=None): Figure.__init__(self) @@ -35,8 +34,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): Figure.__init__(self) @@ -45,8 +43,7 @@ class DiagramEntity(Figure): class ClassDiagram(Figure, FilterMixIn): - """main class diagram handling - """ + """main class diagram handling""" TYPE = "class" @@ -67,14 +64,12 @@ class ClassDiagram(Figure, FilterMixIn): ) def add_relationship(self, from_object, to_object, relation_type, name=None): - """create a relation ship - """ + """create a relation ship""" 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 relation ship or None - """ + """return a relation ship or None""" for rel in self.relationships.get(relation_type, ()): if rel.from_object is from_object: return rel @@ -113,8 +108,7 @@ 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 @@ -137,18 +131,15 @@ 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): @@ -156,16 +147,14 @@ class ClassDiagram(Figure, FilterMixIn): return [o for o in self.objects if isinstance(o.node, astroid.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 relation ships between nodes in the diagram - """ + """extract relation ships between nodes in the diagram""" for obj in self.classes(): node = obj.node obj.attrs = self.get_attrs(node) @@ -206,8 +195,7 @@ class ClassDiagram(Figure, FilterMixIn): class PackageDiagram(ClassDiagram): - """package diagram handling - """ + """package diagram handling""" TYPE = "package" @@ -216,8 +204,7 @@ class PackageDiagram(ClassDiagram): return [o for o in self.objects if isinstance(o.node, astroid.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 @@ -240,16 +227,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 relation ships between nodes in the diagram - """ + """extract relation ships between nodes in the diagram""" ClassDiagram.extract_relationships(self) for obj in self.classes(): # ownership diff --git a/pylint/pyreverse/inspector.py b/pylint/pyreverse/inspector.py index 676da93e9..2258f3d03 100644 --- a/pylint/pyreverse/inspector.py +++ b/pylint/pyreverse/inspector.py @@ -68,13 +68,11 @@ 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 @@ -115,7 +113,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor): def visit_project(self, node): """visit a pyreverse.utils.Project node - * optionally tag the node with a unique id + * optionally tag the node with a unique id """ if self.tag: node.uid = self.generate_id() @@ -125,7 +123,7 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor): def visit_package(self, node): """visit an astroid.Package node - * optionally tag the node with a unique id + * optionally tag the node with a unique id """ if self.tag: node.uid = self.generate_id() @@ -135,9 +133,9 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor): def visit_module(self, node): """visit an astroid.Module node - * set the locals_type mapping - * set the depends mapping - * optionally tag the node with a unique id + * set the locals_type mapping + * set the depends mapping + * optionally tag the node with a unique id """ if hasattr(node, "locals_type"): return @@ -149,9 +147,9 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor): def visit_classdef(self, node): """visit an astroid.Class node - * set the locals_type and instance_attrs_type mappings - * set the implements list and build it - * optionally tag the node with a unique id + * set the locals_type and instance_attrs_type mappings + * set the implements list and build it + * optionally tag the node with a unique id """ if hasattr(node, "locals_type"): return @@ -178,8 +176,8 @@ class Linker(IdGeneratorMixIn, utils.LocalsVisitor): def visit_functiondef(self, node): """visit an astroid.Function node - * set the locals_type mapping - * optionally tag the node with a unique id + * set the locals_type mapping + * optionally tag the node with a unique id """ if hasattr(node, "locals_type"): return diff --git a/pylint/pyreverse/utils.py b/pylint/pyreverse/utils.py index ed0416078..d8ac4f85f 100644 --- a/pylint/pyreverse/utils.py +++ b/pylint/pyreverse/utils.py @@ -41,8 +41,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: @@ -57,8 +56,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): @@ -120,8 +118,7 @@ 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" @@ -134,8 +131,7 @@ 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] diff --git a/pylint/pyreverse/vcgutils.py b/pylint/pyreverse/vcgutils.py index d6dc40484..0b70be782 100644 --- a/pylint/pyreverse/vcgutils.py +++ b/pylint/pyreverse/vcgutils.py @@ -156,36 +156,31 @@ EDGE_ATTRS = { class VCGPrinter: - """A vcg graph writer. - """ + """A vcg graph writer.""" def __init__(self, output_stream): self._stream = output_stream self._indent = "" def open_graph(self, **args): - """open a vcg graph - """ + """open a vcg graph""" self._stream.write("%sgraph:{\n" % self._indent) self._inc_indent() self._write_attributes(GRAPH_ATTRS, **args) def close_graph(self): - """close a vcg graph - """ + """close a vcg graph""" self._dec_indent() self._stream.write("%s}\n" % self._indent) def node(self, title, **args): - """draw a node - """ + """draw a node""" self._stream.write('%snode: {title:"%s"' % (self._indent, title)) self._write_attributes(NODE_ATTRS, **args) self._stream.write("}\n") def edge(self, from_node, to_node, edge_type="", **args): - """draw an edge from a node to another. - """ + """draw an edge from a node to another.""" self._stream.write( '%s%sedge: {sourcename:"%s" targetname:"%s"' % (self._indent, edge_type, from_node, to_node) @@ -196,8 +191,7 @@ class VCGPrinter: # private ################################################################## def _write_attributes(self, attributes_dict, **args): - """write graph, node or edge attributes - """ + """write graph, node or edge attributes""" for key, value in args.items(): try: _type = attributes_dict[key] @@ -222,11 +216,9 @@ correct values are %s""" ) def _inc_indent(self): - """increment indentation - """ + """increment indentation""" self._indent = " %s" % self._indent def _dec_indent(self): - """decrement indentation - """ + """decrement indentation""" self._indent = self._indent[:-2] diff --git a/pylint/pyreverse/writer.py b/pylint/pyreverse/writer.py index 49452f218..b603ab16d 100644 --- a/pylint/pyreverse/writer.py +++ b/pylint/pyreverse/writer.py @@ -20,8 +20,7 @@ from pylint.pyreverse.vcgutils import VCGPrinter class DiagramWriter: - """base class for writing project diagrams - """ + """base class for writing project diagrams""" def __init__(self, config, styles): self.config = config @@ -29,8 +28,7 @@ class DiagramWriter: self.printer = None # defined in set_printer 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 = "%s.%s" % (basename, self.config.output_format) @@ -96,8 +94,7 @@ class DiagramWriter: class DotWriter(DiagramWriter): - """write dot graphs from a diagram definition and a project - """ + """write dot graphs from a diagram definition and a project""" def __init__(self, config): styles = [ @@ -111,8 +108,7 @@ class DotWriter(DiagramWriter): DiagramWriter.__init__(self, config, styles) def set_printer(self, file_name, basename): - """initialize DotWriter and add options for layout. - """ + """initialize DotWriter and add options for layout.""" layout = dict(rankdir="BT") self.printer = DotBackend(basename, additional_param=layout) self.file_name = file_name @@ -148,8 +144,7 @@ class DotWriter(DiagramWriter): class VCGWriter(DiagramWriter): - """write vcg graphs from a diagram definition and a project - """ + """write vcg graphs from a diagram definition and a project""" def __init__(self, config): styles = [ diff --git a/pylint/reporters/reports_handler_mix_in.py b/pylint/reporters/reports_handler_mix_in.py index f420ac609..101f52ea1 100644 --- a/pylint/reporters/reports_handler_mix_in.py +++ b/pylint/reporters/reports_handler_mix_in.py @@ -17,7 +17,7 @@ class ReportsHandlerMixIn: self._reports_state = {} def report_order(self): - """ Return a list of reports, sorted in the order + """Return a list of reports, sorted in the order in which they must be called. """ return list(self._reports) diff --git a/pylint/reporters/ureports/text_writer.py b/pylint/reporters/ureports/text_writer.py index 923fdbec5..c7a213282 100644 --- a/pylint/reporters/ureports/text_writer.py +++ b/pylint/reporters/ureports/text_writer.py @@ -24,8 +24,7 @@ class TextWriter(BaseWriter): self.list_level = 0 def visit_section(self, layout): - """display a section as text - """ + """display a section as text""" self.section += 1 self.writeln() self.format_children(layout) @@ -84,8 +83,7 @@ class TextWriter(BaseWriter): self.write(table_linesep) def visit_verbatimtext(self, layout): - """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) diff --git a/pylint/utils/utils.py b/pylint/utils/utils.py index d7f1bf052..b81807bc4 100644 --- a/pylint/utils/utils.py +++ b/pylint/utils/utils.py @@ -268,7 +268,7 @@ def register_plugins(linter, directory): def get_global_option(checker, option, default=None): - """ Retrieve an option defined by the given *checker* or + """Retrieve an option defined by the given *checker* or by all known option providers. It will look in the list of all options providers diff --git a/tests/benchmark/test_baseline_benchmarks.py b/tests/benchmark/test_baseline_benchmarks.py index d9899ce99..ed9f599d3 100644 --- a/tests/benchmark/test_baseline_benchmarks.py +++ b/tests/benchmark/test_baseline_benchmarks.py @@ -29,40 +29,52 @@ 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. """ + likely to be caused by the pylint system.""" __implements__ = (pylint.interfaces.IRawChecker,) name = "sleeper" - msgs = {"R9999": ("Test", "test-check", "Some helpful text.",)} + msgs = { + "R9999": ( + "Test", + "test-check", + "Some helpful text.", + ) + } sleep_duration = 0.5 # the time to pretend we're doing work for def process_module(self, _astroid): - """ Sleeps for `sleep_duration` on each call + """Sleeps for `sleep_duration` on each call - This effectively means each file costs ~`sleep_duration`+framework overhead """ + This effectively means each file costs ~`sleep_duration`+framework overhead""" time.sleep(self.sleep_duration) 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. """ + likely to be caused by the pylint system.""" __implements__ = (pylint.interfaces.IRawChecker,) name = "long-sleeper" - msgs = {"R9999": ("Test", "test-check", "Some helpful text.",)} + msgs = { + "R9999": ( + "Test", + "test-check", + "Some helpful text.", + ) + } sleep_duration = 0.5 # the time to pretend we're doing work for def process_module(self, _astroid): - """ Sleeps for `sleep_duration` on each call + """Sleeps for `sleep_duration` on each call - This effectively means each file costs ~`sleep_duration`+framework overhead """ + This effectively means each file costs ~`sleep_duration`+framework overhead""" time.sleep(self.sleep_duration) @@ -72,18 +84,26 @@ class NoWorkChecker(BaseChecker): __implements__ = (pylint.interfaces.IRawChecker,) name = "sleeper" - msgs = {"R9999": ("Test", "test-check", "Some helpful text.",)} + msgs = { + "R9999": ( + "Test", + "test-check", + "Some helpful text.", + ) + } def process_module(self, _astroid): pass -@pytest.mark.benchmark(group="baseline",) +@pytest.mark.benchmark( + group="baseline", +) class TestEstablishBaselineBenchmarks: - """ Naive benchmarks for the high-level pylint framework + """Naive benchmarks for the high-level pylint framework Because this benchmarks the fundemental and common parts and changes seen here will - impact everything else """ + impact everything else""" empty_filepath = _empty_filepath() empty_file_info = ( @@ -94,7 +114,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. @@ -105,13 +125,14 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 1 assert len(linter._checkers) == 1, "Should just have 'master'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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. @@ -128,9 +149,10 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 10 assert len(linter._checkers) == 1, "Should have 'master'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % pprint.pformat( + linter.reporter.messages ) def test_baseline_benchmark_check_parallel_j10(self, benchmark): @@ -142,16 +164,17 @@ class TestEstablishBaselineBenchmarks: assert len(linter._checkers) == 1, "Should have 'master'" benchmark(check_parallel, linter, jobs=10, files=fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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 registerd """ + that of the system with a lot of files registerd""" if benchmark.disabled: benchmark(print, "skipping, only benchmark large file counts") return # _only_ run this test is profiling @@ -161,17 +184,18 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 1 assert len(linter._checkers) == 1, "Should have 'master'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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 - the check_parallel system across 10 workers, plus the overhead of PyLinter """ + the check_parallel system across 10 workers, plus the overhead of PyLinter""" if benchmark.disabled: benchmark(print, "skipping, only benchmark large file counts") return # _only_ run this test is profiling @@ -181,16 +205,17 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 10 assert len(linter._checkers) == 1, "Should have 'master'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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 """ + scale""" if benchmark.disabled: benchmark(print, "skipping, only benchmark large file counts") return # _only_ run this test is profiling @@ -201,16 +226,17 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 1 assert len(linter._checkers) == 2, "Should have 'master' and 'sleeper'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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 """ + scale, across workers""" if benchmark.disabled: benchmark(print, "skipping, only benchmark large file counts") return # _only_ run this test is profiling @@ -221,19 +247,20 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 10 assert len(linter._checkers) == 2, "Should have 'master' and 'sleeper'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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 mimick 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. We expect this benchmark to take very close to - `numfiles*SleepingChecker.sleep_duration` """ + `numfiles*SleepingChecker.sleep_duration`""" if benchmark.disabled: benchmark(print, "skipping, do not want to sleep in main tests") return # _only_ run this test is profiling @@ -247,19 +274,20 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 1 assert len(linter._checkers) == 2, "Should have 'master' and 'sleeper'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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)` Because of the cost of the framework and system the performance difference will - *not* be 1/10 of -j1 versions. """ + *not* be 1/10 of -j1 versions.""" if benchmark.disabled: benchmark(print, "skipping, do not want to sleep in main tests") return # _only_ run this test is profiling @@ -274,13 +302,14 @@ class TestEstablishBaselineBenchmarks: assert linter.config.jobs == 10 assert len(linter._checkers) == 2, "Should have 'master' and 'sleeper'" benchmark(linter.check, fileinfos) - assert linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(linter.reporter.messages) + assert ( + linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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. """ @@ -292,13 +321,14 @@ class TestEstablishBaselineBenchmarks: print("len(runner.linter._checkers)", len(runner.linter._checkers)) assert len(runner.linter._checkers) > 1, "Should have more than 'master'" - assert runner.linter.msg_status == 0, ( - "Expected no errors to be thrown: %s" - % pprint.pformat(runner.linter.reporter.messages) + assert ( + runner.linter.msg_status == 0 + ), "Expected no errors to be thrown: %s" % 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_typecheck.py b/tests/checkers/unittest_typecheck.py index e6f82efa9..346f5f38d 100644 --- a/tests/checkers/unittest_typecheck.py +++ b/tests/checkers/unittest_typecheck.py @@ -44,8 +44,7 @@ class TestTypeChecker(CheckerTestCase): CHECKER_CLASS = typecheck.TypeChecker def test_no_member_in_getattr(self): - """Make sure that a module attribute access is checked by pylint. - """ + """Make sure that a module attribute access is checked by pylint.""" node = astroid.extract_node( """ diff --git a/tests/checkers/unittest_variables.py b/tests/checkers/unittest_variables.py index dac9e80f9..f55fdde0d 100644 --- a/tests/checkers/unittest_variables.py +++ b/tests/checkers/unittest_variables.py @@ -128,7 +128,7 @@ class TestVariablesChecker(CheckerTestCase): self.checker.visit_global(node) def test_listcomp_in_decorator(self): - """ Make sure class attributes in scope for listcomp in decorator. + """Make sure class attributes in scope for listcomp in decorator. https://github.com/PyCQA/pylint/issues/511 """ @@ -154,7 +154,7 @@ class TestVariablesChecker(CheckerTestCase): self.walk(module) def test_listcomp_in_ancestors(self): - """ Ensure list comprehensions in base classes are scoped correctly + """Ensure list comprehensions in base classes are scoped correctly https://github.com/PyCQA/pylint/issues/3434 """ @@ -174,7 +174,7 @@ class TestVariablesChecker(CheckerTestCase): self.walk(module) def test_return_type_annotation(self): - """ Make sure class attributes in scope for return type annotations. + """Make sure class attributes in scope for return type annotations. https://github.com/PyCQA/pylint/issues/1976 """ diff --git a/tests/extensions/test_check_docs.py b/tests/extensions/test_check_docs.py index dfb5228de..0ed6cb8a7 100644 --- a/tests/extensions/test_check_docs.py +++ b/tests/extensions/test_check_docs.py @@ -2101,8 +2101,7 @@ class TestParamDocChecker(CheckerTestCase): self.checker.visit_functiondef(node) def test_ignores_raise_notimplementederror_sphinx(self): - """Example of an abstract - """ + """Example of an abstract""" node = astroid.extract_node( """ class Foo(object): diff --git a/tests/lint/unittest_lint.py b/tests/lint/unittest_lint.py index f06adaf0d..d60ea957a 100644 --- a/tests/lint/unittest_lint.py +++ b/tests/lint/unittest_lint.py @@ -534,7 +534,8 @@ def test_load_plugin_config_file(): config_path = join(REGRTEST_DATA_DIR, "dummy_plugin.rc") run = Run( - ["--rcfile", config_path, join(REGRTEST_DATA_DIR, "empty.py")], exit=False, + ["--rcfile", config_path, join(REGRTEST_DATA_DIR, "empty.py")], + exit=False, ) assert ( len([ch.name for ch in run.linter.get_checkers() if ch.name == "dummy_plugin"]) @@ -789,8 +790,7 @@ def test_custom_should_analyze_file(): # are created by the multiprocessing problem. @pytest.mark.parametrize("jobs", [1, 2]) def test_multiprocessing(jobs): - """ Check that multiprocessing does not create duplicates. - """ + """Check that multiprocessing does not create duplicates.""" # For the bug (#3584) to show up we need more than one file with issues # per process filenames = [ diff --git a/tests/test_self.py b/tests/test_self.py index c3a321f2c..cd138e789 100644 --- a/tests/test_self.py +++ b/tests/test_self.py @@ -230,8 +230,7 @@ class TestRunTC: self._runtest([], code=32) def test_no_out_encoding(self): - """test redirection of stdout with non ascii caracters - """ + """test redirection of stdout with non ascii caracters""" # 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 |