fname
stringlengths
63
176
rel_fname
stringclasses
706 values
line
int64
-1
4.5k
name
stringlengths
1
81
kind
stringclasses
2 values
category
stringclasses
2 values
info
stringlengths
0
77.9k
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
725
check_messages
ref
function
@utils.check_messages("yield-outside-function")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
726
visit_yield
def
function
def visit_yield(self, node: nodes.Yield) -> None: self._check_yield_outside_func(node) @utils.check_messages("yield-outside-function") def visit_yieldfrom(self, node: nodes.YieldFrom) -> None: self._check_yield_outside_func(node) @utils.check_messages("not-in-loop", "continue-in-finally") def visit_continue(self, node: nodes.Continue) -> None: self._check_in_loop(node, "continue") @utils.check_messages("not-in-loop") def visit_break(self, node: nodes.Break) -> None: self._check_in_loop(node, "break") @utils.check_messages("useless-else-on-loop") def visit_for(self, node: nodes.For) -> None: self._check_else_on_loop(node) @utils.check_messages("useless-else-on-loop") def visit_while(self, node: nodes.While) -> None: self._check_else_on_loop(node) @utils.check_messages("nonexistent-operator") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Check use of the non-existent ++ and -- operators.""" if ( (node.op in "+-") and isinstance(node.operand, nodes.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2) def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
727
_check_yield_outside_func
ref
function
self._check_yield_outside_func(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
729
check_messages
ref
function
@utils.check_messages("yield-outside-function")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
730
visit_yieldfrom
def
function
def visit_yieldfrom(self, node: nodes.YieldFrom) -> None: self._check_yield_outside_func(node) @utils.check_messages("not-in-loop", "continue-in-finally") def visit_continue(self, node: nodes.Continue) -> None: self._check_in_loop(node, "continue") @utils.check_messages("not-in-loop") def visit_break(self, node: nodes.Break) -> None: self._check_in_loop(node, "break") @utils.check_messages("useless-else-on-loop") def visit_for(self, node: nodes.For) -> None: self._check_else_on_loop(node) @utils.check_messages("useless-else-on-loop") def visit_while(self, node: nodes.While) -> None: self._check_else_on_loop(node) @utils.check_messages("nonexistent-operator") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Check use of the non-existent ++ and -- operators.""" if ( (node.op in "+-") and isinstance(node.operand, nodes.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2) def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
731
_check_yield_outside_func
ref
function
self._check_yield_outside_func(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
733
check_messages
ref
function
@utils.check_messages("not-in-loop", "continue-in-finally")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
734
visit_continue
def
function
def visit_continue(self, node: nodes.Continue) -> None: self._check_in_loop(node, "continue") @utils.check_messages("not-in-loop") def visit_break(self, node: nodes.Break) -> None: self._check_in_loop(node, "break") @utils.check_messages("useless-else-on-loop") def visit_for(self, node: nodes.For) -> None: self._check_else_on_loop(node) @utils.check_messages("useless-else-on-loop") def visit_while(self, node: nodes.While) -> None: self._check_else_on_loop(node) @utils.check_messages("nonexistent-operator") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Check use of the non-existent ++ and -- operators.""" if ( (node.op in "+-") and isinstance(node.operand, nodes.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2) def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
735
_check_in_loop
ref
function
self._check_in_loop(node, "continue")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
737
check_messages
ref
function
@utils.check_messages("not-in-loop")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
738
visit_break
def
function
def visit_break(self, node: nodes.Break) -> None: self._check_in_loop(node, "break") @utils.check_messages("useless-else-on-loop") def visit_for(self, node: nodes.For) -> None: self._check_else_on_loop(node) @utils.check_messages("useless-else-on-loop") def visit_while(self, node: nodes.While) -> None: self._check_else_on_loop(node) @utils.check_messages("nonexistent-operator") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Check use of the non-existent ++ and -- operators.""" if ( (node.op in "+-") and isinstance(node.operand, nodes.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2) def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
739
_check_in_loop
ref
function
self._check_in_loop(node, "break")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
741
check_messages
ref
function
@utils.check_messages("useless-else-on-loop")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
742
visit_for
def
function
def visit_for(self, node: nodes.For) -> None: self._check_else_on_loop(node) @utils.check_messages("useless-else-on-loop") def visit_while(self, node: nodes.While) -> None: self._check_else_on_loop(node) @utils.check_messages("nonexistent-operator") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Check use of the non-existent ++ and -- operators.""" if ( (node.op in "+-") and isinstance(node.operand, nodes.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2) def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
743
_check_else_on_loop
ref
function
self._check_else_on_loop(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
745
check_messages
ref
function
@utils.check_messages("useless-else-on-loop")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
746
visit_while
def
function
def visit_while(self, node: nodes.While) -> None: self._check_else_on_loop(node) @utils.check_messages("nonexistent-operator") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Check use of the non-existent ++ and -- operators.""" if ( (node.op in "+-") and isinstance(node.operand, nodes.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2) def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
747
_check_else_on_loop
ref
function
self._check_else_on_loop(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
749
check_messages
ref
function
@utils.check_messages("nonexistent-operator")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
750
visit_unaryop
def
function
def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Check use of the non-existent ++ and -- operators.""" if ( (node.op in "+-") and isinstance(node.operand, nodes.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2) def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
757
add_message
ref
function
self.add_message("nonexistent-operator", node=node, args=node.op * 2)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
759
_check_nonlocal_without_binding
def
function
def _check_nonlocal_without_binding(self, node, name): current_scope = node.scope() while _True: if current_scope.parent is None: break if not isinstance(current_scope, (nodes.ClassDef, nodes.FunctionDef)): self.add_message("nonlocal-without-binding", args=(name,), node=node) return if name not in current_scope.locals: current_scope = current_scope.parent.scope() continue # Okay, found it. return if not isinstance(current_scope, nodes.FunctionDef): self.add_message("nonlocal-without-binding", args=(name,), node=node) @utils.check_messages("nonlocal-without-binding") def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
760
scope
ref
function
current_scope = node.scope()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
766
add_message
ref
function
self.add_message("nonlocal-without-binding", args=(name,), node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
770
scope
ref
function
current_scope = current_scope.parent.scope()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
777
add_message
ref
function
self.add_message("nonlocal-without-binding", args=(name,), node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
779
check_messages
ref
function
@utils.check_messages("nonlocal-without-binding")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
780
visit_nonlocal
def
function
def visit_nonlocal(self, node: nodes.Nonlocal) -> None: for name in node.names: self._check_nonlocal_without_binding(node, name) @utils.check_messages("abstract-class-instantiated") def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
782
_check_nonlocal_without_binding
ref
function
self._check_nonlocal_without_binding(node, name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
784
check_messages
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
785
visit_call
def
function
def visit_call(self, node: nodes.Call) -> None: """Check instantiating abstract class with abc.ABCMeta as metaclass. """ for inferred in infer_all(node.func): self._check_inferred_class_is_abstract(inferred, node) def _check_inferred_class_is_abstract(self, inferred, node): if not isinstance(inferred, nodes.ClassDef): return klass = utils.node_frame_class(node) if klass is inferred: # Don't emit the warning if the class is instantiated # in its own body or if the call is not an instance # creation. If the class is instantiated into its own # body, we're expecting that it knows what it is doing. return # __init__ was called abstract_methods = _has_abstract_methods(inferred) if not abstract_methods: return metaclass = inferred.metaclass() if metaclass is None: # Python 3.4 has `abc.ABC`, which won't be detected # by ClassNode.metaclass() for ancestor in inferred.ancestors(): if ancestor.qname() == "abc.ABC": self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) break return if metaclass.qname() in ABC_METACLASSES: self.add_message( "abstract-class-instantiated", args=(inferred.name,), node=node ) def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
789
infer_all
ref
function
for inferred in infer_all(node.func):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
790
_check_inferred_class_is_abstract
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
792
_check_inferred_class_is_abstract
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
796
node_frame_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
805
_has_abstract_methods
ref
function
abstract_methods = _has_abstract_methods(inferred)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
810
metaclass
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
815
ancestors
ref
function
for ancestor in inferred.ancestors():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
816
qname
ref
function
if ancestor.qname() == "abc.ABC":
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
817
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
824
qname
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
825
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
829
_check_yield_outside_func
def
function
def _check_yield_outside_func(self, node): if not isinstance(node.frame(future=_True), (nodes.FunctionDef, nodes.Lambda)): self.add_message("yield-outside-function", node=node) def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
830
frame
ref
function
if not isinstance(node.frame(future=True), (nodes.FunctionDef, nodes.Lambda)):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
831
add_message
ref
function
self.add_message("yield-outside-function", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
833
_check_else_on_loop
def
function
def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, ) def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
835
_loop_exits_early
ref
function
if node.orelse and not _loop_exits_early(node):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
836
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
845
_check_in_loop
def
function
def _check_in_loop(self, node, node_name): """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: return if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)): break if ( isinstance(parent, nodes.TryFinally) and node in parent.finalbody and isinstance(node, nodes.Continue) ): self.add_message("continue-in-finally", node=node) 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.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
847
node_ancestors
ref
function
for parent in node.node_ancestors():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
859
add_message
ref
function
self.add_message("continue-in-finally", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
861
add_message
ref
function
self.add_message("not-in-loop", node=node, args=node_name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
863
_check_redefinition
def
function
def _check_redefinition(self, redeftype, node): """Check for redefinition of a function / method / class name.""" parent_frame = node.parent.frame(future=_True) # Ignore function stubs created for type information redefinitions = [ i for i in parent_frame.locals[node.name] if not (isinstance(i.parent, nodes.AnnAssign) and i.parent.simple) ] defined_self = next( (local for local in redefinitions if not utils.is_overload_stub(local)), node, ) if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, nodes.ClassDef) and node.name in REDEFINABLE_METHODS ): return # Skip typing.overload() functions. if utils.is_overload_stub(node): return # Exempt functions redefined on a condition. if isinstance(node.parent, nodes.If): # Exempt "if not <func>" cases if ( isinstance(node.parent.test, nodes.UnaryOp) and node.parent.test.op == "not" and isinstance(node.parent.test.operand, nodes.Name) and node.parent.test.operand.name == node.name ): return # Exempt "if <func> is not None" cases # pylint: disable=too-many-boolean-expressions if ( isinstance(node.parent.test, nodes.Compare) and isinstance(node.parent.test.left, nodes.Name) and node.parent.test.left.name == node.name and node.parent.test.ops[0][0] == "is" and isinstance(node.parent.test.ops[0][1], nodes.Const) and node.parent.test.ops[0][1].value is None ): return # Check if we have forward references for this node. try: redefinition_index = redefinitions.index(node) except ValueError: pass else: for redefinition in redefinitions[:redefinition_index]: inferred = utils.safe_infer(redefinition) if ( inferred and isinstance(inferred, astroid.Instance) and inferred.qname() == TYPING_FORWARD_REF_QNAME ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
865
frame
ref
function
parent_frame = node.parent.frame(future=True)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
874
is_overload_stub
ref
function
(local for local in redefinitions if not utils.is_overload_stub(local)),
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
877
are_exclusive
ref
function
if defined_self is not node and not astroid.are_exclusive(node, defined_self):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
887
is_overload_stub
ref
function
if utils.is_overload_stub(node):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
920
safe_infer
ref
function
inferred = utils.safe_infer(redefinition)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
924
qname
ref
function
and inferred.qname() == TYPING_FORWARD_REF_QNAME
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
928
get_global_option
ref
function
dummy_variables_rgx = lint_utils.get_global_option(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
933
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
940
BasicChecker
def
class
__init__ open visit_if visit_ifexp visit_comprehension _check_using_constant_test visit_module visit_classdef visit_expr _filter_vararg _has_variadic_argument visit_lambda visit_functiondef _check_dangerous_default visit_return visit_continue visit_break visit_raise _check_misplaced_format_function visit_call visit_assert visit_dict visit_tryfinally leave_tryfinally _check_unreachable _check_not_in_finally _check_reversed visit_with _check_self_assigning_variable _check_redeclared_assign_name visit_assign visit_for
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,092
get_global_option
ref
function
py_version = get_global_option(self, "py-version")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,095
reset_node_count
ref
function
self.linter.stats.reset_node_count()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,097
check_messages
ref
function
@utils.check_messages("using-constant-test", "missing-parentheses-for-call-in-test")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,098
visit_if
def
function
def visit_if(self, node: nodes.If) -> None: self._check_using_constant_test(node, node.test) @utils.check_messages("using-constant-test", "missing-parentheses-for-call-in-test") def visit_ifexp(self, node: nodes.IfExp) -> None: self._check_using_constant_test(node, node.test) @utils.check_messages("using-constant-test", "missing-parentheses-for-call-in-test") def visit_comprehension(self, node: nodes.Comprehension) -> None: if node.ifs: for if_test in node.ifs: self._check_using_constant_test(node, if_test) def _check_using_constant_test(self, node, test): const_nodes = ( nodes.Module, nodes.GeneratorExp, nodes.Lambda, nodes.FunctionDef, nodes.ClassDef, astroid.bases.Generator, astroid.UnboundMethod, astroid.BoundMethod, nodes.Module, ) structs = (nodes.Dict, nodes.Tuple, nodes.Set, nodes.List) # These nodes are excepted, since they are not constant # values, requiring a computation to happen. except_nodes = ( nodes.Call, nodes.BinOp, nodes.BoolOp, nodes.UnaryOp, nodes.Subscript, ) inferred = None emit = isinstance(test, (nodes.Const,) + structs + const_nodes) if not isinstance(test, except_nodes): inferred = utils.safe_infer(test) if emit: self.add_message("using-constant-test", node=node) elif isinstance(inferred, const_nodes): # If the constant node is a FunctionDef or Lambda then # it may be an illicit function call due to missing parentheses call_inferred = None try: if isinstance(inferred, nodes.FunctionDef): call_inferred = inferred.infer_call_result() elif isinstance(inferred, nodes.Lambda): call_inferred = inferred.infer_call_result(node) except astroid.InferenceError: call_inferred = None if call_inferred: try: for inf_call in call_inferred: if inf_call != astroid.Uninferable: self.add_message( "missing-parentheses-for-call-in-test", node=node ) break except astroid.InferenceError: pass self.add_message("using-constant-test", node=node) def visit_module(self, _: nodes.Module) -> None: """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 increment branch counter """ self.linter.stats.node_count["klass"] += 1 @utils.check_messages( "pointless-statement", "pointless-string-statement", "expression-not-assigned" ) def visit_expr(self, node: nodes.Expr) -> None: """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 # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance(scope, (nodes.ClassDef, nodes.Module, nodes.FunctionDef)): if isinstance(scope, nodes.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (nodes.Assign, nodes.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yield statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if ( isinstance(expr, (nodes.Yield, nodes.Await, nodes.Call)) or (isinstance(node.parent, nodes.TryExcept) and node.parent.body == [node]) or (isinstance(expr, nodes.Const) and expr.value is Ellipsis) ): return if any(expr.nodes_of_class(nodes.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node) @staticmethod def _filter_vararg(node, call_args): # Return the arguments for the given call which are # not passed as vararg. for arg in call_args: if isinstance(arg, nodes.Starred): if ( isinstance(arg.value, nodes.Name) and arg.value.name != node.args.vararg ): yield arg else: yield arg @staticmethod def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,099
_check_using_constant_test
ref
function
self._check_using_constant_test(node, node.test)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,101
check_messages
ref
function
@utils.check_messages("using-constant-test", "missing-parentheses-for-call-in-test")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,102
visit_ifexp
def
function
def visit_ifexp(self, node: nodes.IfExp) -> None: self._check_using_constant_test(node, node.test) @utils.check_messages("using-constant-test", "missing-parentheses-for-call-in-test") def visit_comprehension(self, node: nodes.Comprehension) -> None: if node.ifs: for if_test in node.ifs: self._check_using_constant_test(node, if_test) def _check_using_constant_test(self, node, test): const_nodes = ( nodes.Module, nodes.GeneratorExp, nodes.Lambda, nodes.FunctionDef, nodes.ClassDef, astroid.bases.Generator, astroid.UnboundMethod, astroid.BoundMethod, nodes.Module, ) structs = (nodes.Dict, nodes.Tuple, nodes.Set, nodes.List) # These nodes are excepted, since they are not constant # values, requiring a computation to happen. except_nodes = ( nodes.Call, nodes.BinOp, nodes.BoolOp, nodes.UnaryOp, nodes.Subscript, ) inferred = None emit = isinstance(test, (nodes.Const,) + structs + const_nodes) if not isinstance(test, except_nodes): inferred = utils.safe_infer(test) if emit: self.add_message("using-constant-test", node=node) elif isinstance(inferred, const_nodes): # If the constant node is a FunctionDef or Lambda then # it may be an illicit function call due to missing parentheses call_inferred = None try: if isinstance(inferred, nodes.FunctionDef): call_inferred = inferred.infer_call_result() elif isinstance(inferred, nodes.Lambda): call_inferred = inferred.infer_call_result(node) except astroid.InferenceError: call_inferred = None if call_inferred: try: for inf_call in call_inferred: if inf_call != astroid.Uninferable: self.add_message( "missing-parentheses-for-call-in-test", node=node ) break except astroid.InferenceError: pass self.add_message("using-constant-test", node=node) def visit_module(self, _: nodes.Module) -> None: """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 increment branch counter """ self.linter.stats.node_count["klass"] += 1 @utils.check_messages( "pointless-statement", "pointless-string-statement", "expression-not-assigned" ) def visit_expr(self, node: nodes.Expr) -> None: """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 # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance(scope, (nodes.ClassDef, nodes.Module, nodes.FunctionDef)): if isinstance(scope, nodes.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (nodes.Assign, nodes.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yield statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if ( isinstance(expr, (nodes.Yield, nodes.Await, nodes.Call)) or (isinstance(node.parent, nodes.TryExcept) and node.parent.body == [node]) or (isinstance(expr, nodes.Const) and expr.value is Ellipsis) ): return if any(expr.nodes_of_class(nodes.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node) @staticmethod def _filter_vararg(node, call_args): # Return the arguments for the given call which are # not passed as vararg. for arg in call_args: if isinstance(arg, nodes.Starred): if ( isinstance(arg.value, nodes.Name) and arg.value.name != node.args.vararg ): yield arg else: yield arg @staticmethod def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,103
_check_using_constant_test
ref
function
self._check_using_constant_test(node, node.test)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,105
check_messages
ref
function
@utils.check_messages("using-constant-test", "missing-parentheses-for-call-in-test")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,106
visit_comprehension
def
function
def visit_comprehension(self, node: nodes.Comprehension) -> None: if node.ifs: for if_test in node.ifs: self._check_using_constant_test(node, if_test) def _check_using_constant_test(self, node, test): const_nodes = ( nodes.Module, nodes.GeneratorExp, nodes.Lambda, nodes.FunctionDef, nodes.ClassDef, astroid.bases.Generator, astroid.UnboundMethod, astroid.BoundMethod, nodes.Module, ) structs = (nodes.Dict, nodes.Tuple, nodes.Set, nodes.List) # These nodes are excepted, since they are not constant # values, requiring a computation to happen. except_nodes = ( nodes.Call, nodes.BinOp, nodes.BoolOp, nodes.UnaryOp, nodes.Subscript, ) inferred = None emit = isinstance(test, (nodes.Const,) + structs + const_nodes) if not isinstance(test, except_nodes): inferred = utils.safe_infer(test) if emit: self.add_message("using-constant-test", node=node) elif isinstance(inferred, const_nodes): # If the constant node is a FunctionDef or Lambda then # it may be an illicit function call due to missing parentheses call_inferred = None try: if isinstance(inferred, nodes.FunctionDef): call_inferred = inferred.infer_call_result() elif isinstance(inferred, nodes.Lambda): call_inferred = inferred.infer_call_result(node) except astroid.InferenceError: call_inferred = None if call_inferred: try: for inf_call in call_inferred: if inf_call != astroid.Uninferable: self.add_message( "missing-parentheses-for-call-in-test", node=node ) break except astroid.InferenceError: pass self.add_message("using-constant-test", node=node) def visit_module(self, _: nodes.Module) -> None: """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 increment branch counter """ self.linter.stats.node_count["klass"] += 1 @utils.check_messages( "pointless-statement", "pointless-string-statement", "expression-not-assigned" ) def visit_expr(self, node: nodes.Expr) -> None: """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 # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance(scope, (nodes.ClassDef, nodes.Module, nodes.FunctionDef)): if isinstance(scope, nodes.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (nodes.Assign, nodes.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yield statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if ( isinstance(expr, (nodes.Yield, nodes.Await, nodes.Call)) or (isinstance(node.parent, nodes.TryExcept) and node.parent.body == [node]) or (isinstance(expr, nodes.Const) and expr.value is Ellipsis) ): return if any(expr.nodes_of_class(nodes.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node) @staticmethod def _filter_vararg(node, call_args): # Return the arguments for the given call which are # not passed as vararg. for arg in call_args: if isinstance(arg, nodes.Starred): if ( isinstance(arg.value, nodes.Name) and arg.value.name != node.args.vararg ): yield arg else: yield arg @staticmethod def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,109
_check_using_constant_test
ref
function
self._check_using_constant_test(node, if_test)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,111
_check_using_constant_test
def
function
def _check_using_constant_test(self, node, test): const_nodes = ( nodes.Module, nodes.GeneratorExp, nodes.Lambda, nodes.FunctionDef, nodes.ClassDef, astroid.bases.Generator, astroid.UnboundMethod, astroid.BoundMethod, nodes.Module, ) structs = (nodes.Dict, nodes.Tuple, nodes.Set, nodes.List) # These nodes are excepted, since they are not constant # values, requiring a computation to happen. except_nodes = ( nodes.Call, nodes.BinOp, nodes.BoolOp, nodes.UnaryOp, nodes.Subscript, ) inferred = None emit = isinstance(test, (nodes.Const,) + structs + const_nodes) if not isinstance(test, except_nodes): inferred = utils.safe_infer(test) if emit: self.add_message("using-constant-test", node=node) elif isinstance(inferred, const_nodes): # If the constant node is a FunctionDef or Lambda then # it may be an illicit function call due to missing parentheses call_inferred = None try: if isinstance(inferred, nodes.FunctionDef): call_inferred = inferred.infer_call_result() elif isinstance(inferred, nodes.Lambda): call_inferred = inferred.infer_call_result(node) except astroid.InferenceError: call_inferred = None if call_inferred: try: for inf_call in call_inferred: if inf_call != astroid.Uninferable: self.add_message( "missing-parentheses-for-call-in-test", node=node ) break except astroid.InferenceError: pass self.add_message("using-constant-test", node=node) def visit_module(self, _: nodes.Module) -> None: """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 increment branch counter """ self.linter.stats.node_count["klass"] += 1 @utils.check_messages( "pointless-statement", "pointless-string-statement", "expression-not-assigned" ) def visit_expr(self, node: nodes.Expr) -> None: """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 # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance(scope, (nodes.ClassDef, nodes.Module, nodes.FunctionDef)): if isinstance(scope, nodes.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (nodes.Assign, nodes.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yield statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if ( isinstance(expr, (nodes.Yield, nodes.Await, nodes.Call)) or (isinstance(node.parent, nodes.TryExcept) and node.parent.body == [node]) or (isinstance(expr, nodes.Const) and expr.value is Ellipsis) ): return if any(expr.nodes_of_class(nodes.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node) @staticmethod def _filter_vararg(node, call_args): # Return the arguments for the given call which are # not passed as vararg. for arg in call_args: if isinstance(arg, nodes.Starred): if ( isinstance(arg.value, nodes.Name) and arg.value.name != node.args.vararg ): yield arg else: yield arg @staticmethod def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,137
safe_infer
ref
function
inferred = utils.safe_infer(test)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,140
add_message
ref
function
self.add_message("using-constant-test", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,147
infer_call_result
ref
function
call_inferred = inferred.infer_call_result()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,149
infer_call_result
ref
function
call_inferred = inferred.infer_call_result(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,156
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,162
add_message
ref
function
self.add_message("using-constant-test", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,164
visit_module
def
function
def visit_module(self, _: nodes.Module) -> None: """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 increment branch counter """ self.linter.stats.node_count["klass"] += 1 @utils.check_messages( "pointless-statement", "pointless-string-statement", "expression-not-assigned" ) def visit_expr(self, node: nodes.Expr) -> None: """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 # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance(scope, (nodes.ClassDef, nodes.Module, nodes.FunctionDef)): if isinstance(scope, nodes.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (nodes.Assign, nodes.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yield statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if ( isinstance(expr, (nodes.Yield, nodes.Await, nodes.Call)) or (isinstance(node.parent, nodes.TryExcept) and node.parent.body == [node]) or (isinstance(expr, nodes.Const) and expr.value is Ellipsis) ): return if any(expr.nodes_of_class(nodes.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node) @staticmethod def _filter_vararg(node, call_args): # Return the arguments for the given call which are # not passed as vararg. for arg in call_args: if isinstance(arg, nodes.Starred): if ( isinstance(arg.value, nodes.Name) and arg.value.name != node.args.vararg ): yield arg else: yield arg @staticmethod def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,168
visit_classdef
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,174
check_messages
ref
function
@utils.check_messages(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,177
visit_expr
def
function
def visit_expr(self, node: nodes.Expr) -> None: """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 # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance(scope, (nodes.ClassDef, nodes.Module, nodes.FunctionDef)): if isinstance(scope, nodes.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (nodes.Assign, nodes.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yield statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if ( isinstance(expr, (nodes.Yield, nodes.Await, nodes.Call)) or (isinstance(node.parent, nodes.TryExcept) and node.parent.body == [node]) or (isinstance(expr, nodes.Const) and expr.value is Ellipsis) ): return if any(expr.nodes_of_class(nodes.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node) @staticmethod def _filter_vararg(node, call_args): # Return the arguments for the given call which are # not passed as vararg. for arg in call_args: if isinstance(arg, nodes.Starred): if ( isinstance(arg.value, nodes.Name) and arg.value.name != node.args.vararg ): yield arg else: yield arg @staticmethod def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,185
scope
ref
function
scope = expr.scope()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,190
previous_sibling
ref
function
sibling = expr.previous_sibling()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,193
scope
ref
function
and sibling.scope() is scope
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,197
add_message
ref
function
self.add_message("pointless-string-statement", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,213
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,214
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,215
as_string
ref
function
"expression-not-assigned", node=node, args=expr.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,218
add_message
ref
function
self.add_message("pointless-statement", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,221
_filter_vararg
def
function
def _filter_vararg(node, call_args): # Return the arguments for the given call which are # not passed as vararg. for arg in call_args: if isinstance(arg, nodes.Starred): if ( isinstance(arg.value, nodes.Name) and arg.value.name != node.args.vararg ): yield arg else: yield arg @staticmethod def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,235
_has_variadic_argument
def
function
def _has_variadic_argument(args, variadic_name): if not args: return _True for arg in args: if isinstance(arg.value, nodes.Name): if arg.value.name != variadic_name: return _True else: return _True return _False @utils.check_messages("unnecessary-lambda") def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,246
check_messages
ref
function
@utils.check_messages("unnecessary-lambda")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,247
visit_lambda
def
function
def visit_lambda(self, node: nodes.Lambda) -> None: """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. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, nodes.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, nodes.Attribute) and isinstance( node.body.func.expr, nodes.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = astroid.arguments.CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, nodes.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node) @utils.check_messages("dangerous-default-value") def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check function name, docstring, arguments, redefinition, variable names, max locals """ if node.is_method(): self.linter.stats.node_count["method"] += 1 else: self.linter.stats.node_count["function"] += 1 self._check_dangerous_default(node) visit_asyncfunctiondef = visit_functiondef def _check_dangerous_default(self, node): """Check for dangerous default values as arguments.""" def is_iterable(internal_node): return isinstance(internal_node, (nodes.List, nodes.Set, nodes.Dict)) defaults = node.args.defaults or [] + node.args.kw_defaults or [] for default in defaults: if not default: continue try: value = next(default.infer()) except astroid.InferenceError: continue if ( isinstance(value, astroid.Instance) and value.qname() in DEFAULT_ARGUMENT_SYMBOLS ): if value is default: msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()] elif isinstance(value, astroid.Instance) or is_iterable(value): # We are here in the following situation(s): # * a dict/set/list/tuple call which wasn't inferred # to a syntax node ({}, () etc.). This can happen # when the arguments are invalid or unknown to # the inference. # * a variable from somewhere else, which turns out to be a list # or a dict. if is_iterable(default): msg = value.pytype() elif isinstance(default, nodes.Call): msg = f"{value.name}() ({value.qname()})" else: msg = f"{default.as_string()} ({value.qname()})" else: # this argument is a name msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})" self.add_message("dangerous-default-value", node=node, args=(msg,)) @utils.check_messages("unreachable", "lost-exception") def visit_return(self, node: nodes.Return) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ self._check_unreachable(node) # Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "return", (nodes.FunctionDef,)) @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 code) """ self._check_unreachable(node) @utils.check_messages("unreachable", "lost-exception") def visit_break(self, node: nodes.Break) -> None: """1 - check if the node has a right sibling (if so, that's some unreachable code) 2 - check if the node is inside the 'finally' clause of a 'try...finally' block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally block ? self._check_not_in_finally(node, "break", (nodes.For, nodes.While)) @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 code) """ self._check_unreachable(node) def _check_misplaced_format_function(self, call_node): if not isinstance(call_node.func, nodes.Attribute): return if call_node.func.attrname != "format": return expr = utils.safe_infer(call_node.func.expr) if expr is astroid.Uninferable: return if not expr: # we are doubtful on inferred type of node, so here just check if format # was called on print() call_expr = call_node.func.expr if not isinstance(call_expr, nodes.Call): return if ( isinstance(call_expr.func, nodes.Name) and call_expr.func.name == "print" ): self.add_message("misplaced-format-function", node=call_node) @utils.check_messages( "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 call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node) @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.""" if ( node.fail is None and isinstance(node.test, nodes.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node) if isinstance(node.test, nodes.Const) and isinstance(node.test.value, str): if node.test.value: when = "never" else: when = "always" self.add_message("assert-on-string-literal", node=node, args=(when,)) @utils.check_messages("duplicate-key") def visit_dict(self, node: nodes.Dict) -> None: """Check duplicate key in dictionary.""" keys = set() for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value elif isinstance(k, nodes.Attribute): key = k.as_string() else: continue if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.append(node) def leave_tryfinally(self, _: nodes.TryFinally) -> None: """Update try...finally flag.""" self._tryfinallys.pop() def _check_unreachable(self, node): """Check unreachable code.""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: if ( isinstance(node, nodes.Return) and isinstance(unreach_stmt, nodes.Expr) and isinstance(unreach_stmt.value, nodes.Yield) ): # Don't add 'unreachable' for empty generators. # Only add warning if 'yield' is followed by another node. unreach_stmt = unreach_stmt.next_sibling() if unreach_stmt is None: return 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 'try...finally' statement. If we find a parent which type is in breaker_classes before a 'try...finally' block we skip the whole check. """ # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-child of the 'try...finally' _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent def _check_reversed(self, node): """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: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was inferred. # Try to see if we have iter(). if isinstance(node.args[0], nodes.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (nodes.List, nodes.Tuple)): return # dicts are reversible, but only from Python 3.8 onwards. Prior to # that, any class based on dict must explicitly provide a # __reversed__ method if not self._py38_plus and isinstance(argument, astroid.Instance): if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in itertools.chain( (argument._proxied,), argument._proxied.ancestors() ) ): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node) @utils.check_messages("confusing-with-statement") def visit_with(self, node: nodes.With) -> None: # a "with" statement with multiple managers corresponds # to one AST "With" node with multiple items pairs = node.items if pairs: for prev_pair, pair in zip(pairs, pairs[1:]): if isinstance(prev_pair[1], nodes.AssignName) and ( pair[1] is None and not isinstance(pair[0], nodes.Call) ): # Don't emit a message if the second is a function call # there's no way that can be mistaken for a name assignment. # If the line number doesn't match # we assume it's a nested "with". self.add_message("confusing-with-statement", node=node) def _check_self_assigning_variable(self, node): # Detect assigning to the same variable. scope = node.scope() scope_locals = scope.locals rhs_names = [] targets = node.targets if isinstance(targets[0], nodes.Tuple): if len(targets) != 1: # A complex assignment, so bail out early. return targets = targets[0].elts if len(targets) == 1: # Unpacking a variable into the same name. return if isinstance(node.value, nodes.Name): if len(targets) != 1: return rhs_names = [node.value] elif isinstance(node.value, nodes.Tuple): rhs_count = len(node.value.elts) if len(targets) != rhs_count or rhs_count == 1: return rhs_names = node.value.elts for target, lhs_name in zip(targets, rhs_names): if not isinstance(lhs_name, nodes.Name): continue if not isinstance(target, nodes.AssignName): continue # Check that the scope is different from a class level, which is usually # a pattern to expose module level attributes as class level ones. if isinstance(scope, nodes.ClassDef) and target.name in scope_locals: continue if target.name == lhs_name.name: self.add_message( "self-assigning-variable", args=(target.name,), node=target ) def _check_redeclared_assign_name(self, targets): dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) for target in targets: if not isinstance(target, nodes.Tuple): continue found_names = [] for element in target.elts: if isinstance(element, nodes.Tuple): self._check_redeclared_assign_name([element]) elif isinstance(element, nodes.AssignName) and element.name != "_": if dummy_variables_rgx and dummy_variables_rgx.match(element.name): return found_names.append(element.name) names = collections.Counter(found_names) for name, count in names.most_common(): if count > 1: self.add_message( "redeclared-assigned-name", args=(name,), node=target ) @utils.check_messages("self-assigning-variable", "redeclared-assigned-name") def visit_assign(self, node: nodes.Assign) -> None: self._check_self_assigning_variable(node) self._check_redeclared_assign_name(node.targets) @utils.check_messages("redeclared-assigned-name") def visit_for(self, node: nodes.For) -> None: self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,271
from_call
ref
function
call_site = astroid.arguments.CallSite.from_call(call)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,273
_filter_vararg
ref
function
new_call_args = list(self._filter_vararg(node, call.args))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,275
_has_variadic_argument
ref
function
if self._has_variadic_argument(call.kwargs, node.args.kwarg):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,279
_has_variadic_argument
ref
function
if self._has_variadic_argument(call.starargs, node.args.vararg):