diff options
author | Nick Drozd <nicholasdrozd@gmail.com> | 2021-10-25 09:36:39 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-10-25 16:36:39 +0200 |
commit | b6ca3b9d6f7ad42accdf90044628521bd711d1ec (patch) | |
tree | 493df3452dc727f4bfce142e4d856471d8abbeb4 | |
parent | 8cfce138e9519f63e969e89359e86e140b2f0f13 (diff) | |
download | pylint-git-b6ca3b9d6f7ad42accdf90044628521bd711d1ec.tar.gz |
Enable for_any_all check (#5206)
* Enable for_any_all check, reword a few docstrings, shorten some loop variable
names, and add typing on modified functions.
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
Co-authored-by: Daniƫl van Noord <13665637+DanielNoord@users.noreply.github.com>
-rw-r--r-- | pylint/checkers/base.py | 27 | ||||
-rw-r--r-- | pylint/checkers/exceptions.py | 7 | ||||
-rw-r--r-- | pylint/checkers/logging.py | 15 | ||||
-rw-r--r-- | pylint/checkers/refactoring/refactoring_checker.py | 13 | ||||
-rw-r--r-- | pylint/checkers/spelling.py | 5 | ||||
-rw-r--r-- | pylint/checkers/utils.py | 33 | ||||
-rw-r--r-- | pylint/checkers/variables.py | 25 | ||||
-rw-r--r-- | pylint/interfaces.py | 7 | ||||
-rw-r--r-- | pylint/lint/expand_modules.py | 5 | ||||
-rw-r--r-- | pylint/lint/pylinter.py | 7 | ||||
-rw-r--r-- | pylint/utils/ast_walker.py | 5 | ||||
-rw-r--r-- | pylintrc | 1 |
12 files changed, 54 insertions, 96 deletions
diff --git a/pylint/checkers/base.py b/pylint/checkers/base.py index 699f2dae1..d6a59f38b 100644 --- a/pylint/checkers/base.py +++ b/pylint/checkers/base.py @@ -242,21 +242,18 @@ def _redefines_import(node): return False -def in_loop(node): - """return True if the node is inside a kind of for loop""" - for parent in node.node_ancestors(): - if isinstance( - parent, - ( - nodes.For, - nodes.ListComp, - nodes.SetComp, - nodes.DictComp, - nodes.GeneratorExp, - ), - ): - return True - return False +LOOPLIKE_NODES = ( + nodes.For, + nodes.ListComp, + nodes.SetComp, + nodes.DictComp, + nodes.GeneratorExp, +) + + +def in_loop(node: nodes.NodeNG) -> bool: + """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): diff --git a/pylint/checkers/exceptions.py b/pylint/checkers/exceptions.py index 2e26c31a0..c12657809 100644 --- a/pylint/checkers/exceptions.py +++ b/pylint/checkers/exceptions.py @@ -72,11 +72,8 @@ def _annotated_unpack_infer(stmt, context=None): def _is_raising(body: List) -> bool: - """Return true if the given statement node raise an exception""" - for node in body: - if isinstance(node, nodes.Raise): - return True - return False + """Return whether the given statement node raises an exception""" + return any(isinstance(node, nodes.Raise) for node in body) OVERGENERAL_EXCEPTIONS = ("BaseException", "Exception") diff --git a/pylint/checkers/logging.py b/pylint/checkers/logging.py index e04b0ec8f..e1dd383e5 100644 --- a/pylint/checkers/logging.py +++ b/pylint/checkers/logging.py @@ -369,14 +369,8 @@ class LoggingChecker(checkers.BaseChecker): self.add_message("logging-too-few-args", node=node) -def is_complex_format_str(node): - """Checks if node represents a string with complex formatting specs. - - Args: - node (nodes.NodeNG): AST node to check - Returns: - bool: True if inferred string uses complex formatting, False otherwise - """ +def is_complex_format_str(node: nodes.NodeNG) -> bool: + """Return whether the node represents a string with complex formatting specs.""" inferred = utils.safe_infer(node) if inferred is None or not ( isinstance(inferred, nodes.Const) and isinstance(inferred.value, str) @@ -387,10 +381,7 @@ def is_complex_format_str(node): except ValueError: # This format string is invalid return False - for _, _, format_spec, _ in parsed: - if format_spec: - return True - return False + return any(format_spec for (_, _, format_spec, _) in parsed) def _count_supplied_tokens(args): diff --git a/pylint/checkers/refactoring/refactoring_checker.py b/pylint/checkers/refactoring/refactoring_checker.py index 4c7842d8b..e8e403e1b 100644 --- a/pylint/checkers/refactoring/refactoring_checker.py +++ b/pylint/checkers/refactoring/refactoring_checker.py @@ -49,10 +49,7 @@ CALLS_RETURNING_CONTEXT_MANAGERS = frozenset( def _if_statement_is_always_returning(if_node, returning_node_class) -> bool: - for node in if_node.body: - if isinstance(node, returning_node_class): - return True - return False + return any(isinstance(node, returning_node_class) for node in if_node.body) def _is_trailing_comma(tokens: List[tokenize.TokenInfo], index: int) -> bool: @@ -97,10 +94,10 @@ def _is_trailing_comma(tokens: List[tokenize.TokenInfo], index: int) -> bool: curline_start = get_curline_index_start() expected_tokens = {"return", "yield"} - for prevtoken in tokens[curline_start:index]: - if "=" in prevtoken.string or prevtoken.string in expected_tokens: - return True - return False + return any( + "=" in prevtoken.string or prevtoken.string in expected_tokens + for prevtoken in tokens[curline_start:index] + ) def _is_inside_context_manager(node: nodes.Call) -> bool: diff --git a/pylint/checkers/spelling.py b/pylint/checkers/spelling.py index 3b2973ffa..b26b5edd6 100644 --- a/pylint/checkers/spelling.py +++ b/pylint/checkers/spelling.py @@ -91,10 +91,7 @@ class WordsWithDigitsFilter(Filter): """Skips words with digits.""" def _skip(self, word): - for char in word: - if char.isdigit(): - return True - return False + return any(char.isdigit() for char in word) class WordsWithUnderscores(Filter): diff --git a/pylint/checkers/utils.py b/pylint/checkers/utils.py index 1d198e87e..3361eef8a 100644 --- a/pylint/checkers/utils.py +++ b/pylint/checkers/utils.py @@ -285,11 +285,8 @@ class InferredTypeError(Exception): def is_inside_lambda(node: nodes.NodeNG) -> bool: - """Return true if given node is inside lambda""" - for parent in node.node_ancestors(): - if isinstance(parent, nodes.Lambda): - return True - return False + """Return whether the given node is inside a lambda""" + return any(isinstance(parent, nodes.Lambda) for parent in node.node_ancestors()) def get_all_elements( @@ -443,15 +440,12 @@ def is_func_decorator(node: nodes.NodeNG) -> bool: def is_ancestor_name(frame: nodes.ClassDef, node: nodes.NodeNG) -> bool: - """return True if `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): return False - for base in frame.bases: - if node in base.nodes_of_class(nodes.Name): - return True - return False + return any(node in base.nodes_of_class(nodes.Name) for base in frame.bases) def is_being_called(node: nodes.NodeNG) -> bool: @@ -719,17 +713,15 @@ def get_argument_from_call( def inherit_from_std_ex(node: nodes.NodeNG) -> bool: """ - Return true if the given class node is subclass of + Return whether the given class node is subclass of exceptions.Exception. """ ancestors = node.ancestors() if hasattr(node, "ancestors") else [] - for ancestor in itertools.chain([node], ancestors): - if ( - ancestor.name in ("Exception", "BaseException") - and ancestor.root().name == EXCEPTIONS_MODULE - ): - return True - return False + return any( + ancestor.name in ("Exception", "BaseException") + and ancestor.root().name == EXCEPTIONS_MODULE + for ancestor in itertools.chain([node], ancestors) + ) def error_of_type(handler: nodes.ExceptHandler, error_type) -> bool: @@ -1444,10 +1436,7 @@ def is_classdef_type(node: nodes.ClassDef) -> bool: """Test if ClassDef node is Type.""" if node.name == "type": return True - for base in node.bases: - if isinstance(base, nodes.Name) and base.name == "type": - return True - return False + return any(isinstance(b, nodes.Name) and b.name == "type" for b in node.bases) def is_attribute_typed_annotation( diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index bbcf855a3..4851421b2 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -1951,23 +1951,24 @@ class VariablesChecker(BaseChecker): def _allowed_redefined_builtin(self, name): return name in self.config.allowed_redefined_builtins - def _has_homonym_in_upper_function_scope(self, node, index): + def _has_homonym_in_upper_function_scope( + self, node: nodes.Name, index: int + ) -> bool: """ - Return True if there is a node with the same name in the to_consume dict of an upper scope - and if that scope is a function + Return whether there is a node with the same name in the + to_consume dict of an upper scope and if that scope is a + function :param node: node to check for - :type node: astroid.Node :param index: index of the current consumer inside self._to_consume - :type index: int - :return: True if there is a node with the same name in the to_consume dict of an upper scope - and if that scope is a function - :rtype: bool + :return: True if there is a node with the same name in the + to_consume dict of an upper scope and if that scope + is a function, False otherwise """ - for _consumer in self._to_consume[index - 1 :: -1]: - if _consumer.scope_type == "function" and node.name in _consumer.to_consume: - return True - return False + return any( + _consumer.scope_type == "function" and node.name in _consumer.to_consume + for _consumer in self._to_consume[index - 1 :: -1] + ) def _store_type_annotation_node(self, type_annotation): """Given a type annotation, store all the name nodes it refers to""" diff --git a/pylint/interfaces.py b/pylint/interfaces.py index e657e7115..5b813c7b7 100644 --- a/pylint/interfaces.py +++ b/pylint/interfaces.py @@ -46,16 +46,13 @@ class Interface: def implements(obj: "Interface", interface: Tuple[type, type]) -> bool: - """Return true if the give object (maybe an instance or class) implements + """Return whether the given object (maybe an instance or class) implements the interface. """ kimplements = getattr(obj, "__implements__", ()) if not isinstance(kimplements, (list, tuple)): kimplements = (kimplements,) - for implementedinterface in kimplements: - if issubclass(implementedinterface, interface): - return True - return False + return any(issubclass(i, interface) for i in kimplements) class IChecker(Interface): diff --git a/pylint/lint/expand_modules.py b/pylint/lint/expand_modules.py index cea4b5c17..8eaf98847 100644 --- a/pylint/lint/expand_modules.py +++ b/pylint/lint/expand_modules.py @@ -33,10 +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""" - for file_pattern in ignore_list_re: - if file_pattern.match(element): - return True - return False + return any(file_pattern.match(element) for file_pattern in ignore_list_re) def expand_modules( diff --git a/pylint/lint/pylinter.py b/pylint/lint/pylinter.py index 3be78c46c..ae2126c09 100644 --- a/pylint/lint/pylinter.py +++ b/pylint/lint/pylinter.py @@ -1389,7 +1389,7 @@ class PyLinter( line: Optional[int] = None, confidence: Optional[interfaces.Confidence] = None, ) -> bool: - """return true if the message associated to the given message id is + """return whether the message associated to the given message id is enabled msgid may be either a numeric or symbolic message id. @@ -1405,10 +1405,7 @@ class PyLinter( # due to version mismatch, just treat them as message IDs # for now. msgids = [msg_descr] - for msgid in msgids: - if self._is_one_message_enabled(msgid, line): - return True - return False + return any(self._is_one_message_enabled(msgid, line) for msgid in msgids) def _add_one_message( self, diff --git a/pylint/utils/ast_walker.py b/pylint/utils/ast_walker.py index 756889251..4f76a9805 100644 --- a/pylint/utils/ast_walker.py +++ b/pylint/utils/ast_walker.py @@ -19,10 +19,7 @@ class ASTWalker: def _is_method_enabled(self, method): if not hasattr(method, "checks_msgs"): return True - for msg_desc in method.checks_msgs: - if self.linter.is_message_enabled(msg_desc): - return True - return False + 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""" @@ -19,6 +19,7 @@ persistent=yes load-plugins= pylint.extensions.check_elif, pylint.extensions.bad_builtin, + pylint.extensions.for_any_all, pylint.extensions.code_style, pylint.extensions.overlapping_exceptions, pylint.extensions.typing, |