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
1,304
add_message
ref
function
self.add_message("unnecessary-lambda", line=node.fromlineno, node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,306
check_messages
ref
function
@utils.check_messages("dangerous-default-value")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,307
visit_functiondef
def
function
def visit_functiondef(self, node: nodes.FunctionDef) -> None: self._check_nonlocal_and_global(node) self._check_name_used_prior_global(node) if not redefined_by_decorator( node ) and not utils.is_registered_in_singledispatch_function(node): self._check_redefinition(node.is_method() and "method" or "function", node) # checks for max returns, branch, return in __init__ returns = node.nodes_of_class( nodes.Return, skip_klass=(nodes.FunctionDef, nodes.ClassDef) ) if node.is_method() and node.name == "__init__": if node.is_generator(): self.add_message("init-is-generator", node=node) else: values = [r.value for r in returns] # Are we returning anything but None from constructors if any(v for v in values if not utils.is_none(v)): self.add_message("return-in-init", node=node) # Check for duplicate names by clustering args with same name for detailed report arg_clusters = collections.defaultdict(list) arguments: Iterator[Any] = filter(None, [node.args.args, node.args.kwonlyargs]) for arg in itertools.chain.from_iterable(arguments): arg_clusters[arg.name].append(arg) # provide detailed report about each repeated argument for argument_duplicates in arg_clusters.values(): if len(argument_duplicates) != 1: for argument in argument_duplicates: self.add_message( "duplicate-argument-name", line=argument.lineno, node=argument, args=(argument.name,), ) visit_asyncfunctiondef = visit_functiondef def _check_name_used_prior_global(self, node): scope_globals = { name: child for child in node.nodes_of_class(nodes.Global) for name in child.names if child.scope() is node } if not scope_globals: return for node_name in node.nodes_of_class(nodes.Name): if node_name.scope() is not node: continue name = node_name.name corresponding_global = scope_globals.get(name) if not corresponding_global: continue global_lineno = corresponding_global.fromlineno if global_lineno and global_lineno > node_name.fromlineno: self.add_message( "used-prior-global-declaration", node=node_name, args=(name,) ) def _check_nonlocal_and_global(self, node): """Check that a name is both nonlocal and global.""" def same_scope(current): return current.scope() is node from_iter = itertools.chain.from_iterable nonlocals = set( from_iter( child.names for child in node.nodes_of_class(nodes.Nonlocal) if same_scope(child) ) ) if not nonlocals: return global_vars = set( from_iter( child.names for child in node.nodes_of_class(nodes.Global) if same_scope(child) ) ) for name in nonlocals.intersection(global_vars): self.add_message("nonlocal-and-global", args=(name,), node=node) @utils.check_messages("return-outside-function") def visit_return(self, node: nodes.Return) -> None: if not isinstance(node.frame(future=_True), nodes.FunctionDef): self.add_message("return-outside-function", node=node) @utils.check_messages("yield-outside-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
1,311
is_method
ref
function
if node.is_method():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,315
_check_dangerous_default
ref
function
self._check_dangerous_default(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,319
_check_dangerous_default
def
function
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,322
is_iterable
def
function
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,330
infer
ref
function
value = next(default.infer())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,336
qname
ref
function
and value.qname() in DEFAULT_ARGUMENT_SYMBOLS
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,339
qname
ref
function
msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,340
is_iterable
ref
function
elif isinstance(value, astroid.Instance) or is_iterable(value):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,348
is_iterable
ref
function
if is_iterable(default):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,349
pytype
ref
function
msg = value.pytype()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,351
qname
ref
function
msg = f"{value.name}() ({value.qname()})"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,353
as_string
ref
function
msg = f"{default.as_string()} ({value.qname()})"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,353
qname
ref
function
msg = f"{default.as_string()} ({value.qname()})"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,356
as_string
ref
function
msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,356
qname
ref
function
msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,357
add_message
ref
function
self.add_message("dangerous-default-value", node=node, args=(msg,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,359
check_messages
ref
function
@utils.check_messages("unreachable", "lost-exception")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,360
visit_return
def
function
def visit_return(self, node: nodes.Return) -> None: if not isinstance(node.frame(future=_True), nodes.FunctionDef): self.add_message("return-outside-function", node=node) @utils.check_messages("yield-outside-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
1,366
_check_unreachable
ref
function
self._check_unreachable(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,368
_check_not_in_finally
ref
function
self._check_not_in_finally(node, "return", (nodes.FunctionDef,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,370
check_messages
ref
function
@utils.check_messages("unreachable")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,371
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
1,375
_check_unreachable
ref
function
self._check_unreachable(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,377
check_messages
ref
function
@utils.check_messages("unreachable", "lost-exception")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,378
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
1,385
_check_unreachable
ref
function
self._check_unreachable(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,387
_check_not_in_finally
ref
function
self._check_not_in_finally(node, "break", (nodes.For, nodes.While))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,389
check_messages
ref
function
@utils.check_messages("unreachable")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,390
visit_raise
def
function
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,394
_check_unreachable
ref
function
self._check_unreachable(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,396
_check_misplaced_format_function
def
function
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,402
safe_infer
ref
function
expr = utils.safe_infer(call_node.func.expr)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,415
add_message
ref
function
self.add_message("misplaced-format-function", node=call_node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,417
check_messages
ref
function
@utils.check_messages(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,420
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
1,424
_check_misplaced_format_function
ref
function
self._check_misplaced_format_function(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,429
frame
ref
function
if not (name in node.frame(future=True) or name in node.root()):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,429
root
ref
function
if not (name in node.frame(future=True) or name in node.root()):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,431
add_message
ref
function
self.add_message("exec-used", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,433
_check_reversed
ref
function
self._check_reversed(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,435
add_message
ref
function
self.add_message("eval-used", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,437
check_messages
ref
function
@utils.check_messages("assert-on-tuple", "assert-on-string-literal")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,438
visit_assert
def
function
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,445
add_message
ref
function
self.add_message("assert-on-tuple", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,452
add_message
ref
function
self.add_message("assert-on-string-literal", node=node, args=(when,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,454
check_messages
ref
function
@utils.check_messages("duplicate-key")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,455
visit_dict
def
function
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,462
as_string
ref
function
key = k.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,466
add_message
ref
function
self.add_message("duplicate-key", node=node, args=key)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,469
visit_tryfinally
def
function
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,473
leave_tryfinally
def
function
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,477
_check_unreachable
def
function
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,479
next_sibling
ref
function
unreach_stmt = node.next_sibling()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,488
next_sibling
ref
function
unreach_stmt = unreach_stmt.next_sibling()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,491
add_message
ref
function
self.add_message("unreachable", node=unreach_stmt)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,493
_check_not_in_finally
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,507
add_message
ref
function
self.add_message("lost-exception", node=node, args=node_name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,512
_check_reversed
def
function
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,515
safe_infer
ref
function
argument = utils.safe_infer(utils.get_argument_from_call(node, position=0))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,515
get_argument_from_call
ref
function
argument = utils.safe_infer(utils.get_argument_from_call(node, position=0))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,526
infer
ref
function
func = next(node.args[0].func.infer())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,531
is_builtin_object
ref
function
) == "iter" and utils.is_builtin_object(func):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,532
add_message
ref
function
self.add_message("bad-reversed-sequence", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,543
is_builtin_object
ref
function
ancestor.name == "dict" and utils.is_builtin_object(ancestor)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,545
ancestors
ref
function
(argument._proxied,), argument._proxied.ancestors()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,551
add_message
ref
function
self.add_message("bad-reversed-sequence", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,565
add_message
ref
function
self.add_message("bad-reversed-sequence", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,567
add_message
ref
function
self.add_message("bad-reversed-sequence", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,569
check_messages
ref
function
@utils.check_messages("confusing-with-statement")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,570
visit_with
def
function
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,583
add_message
ref
function
self.add_message("confusing-with-statement", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,585
_check_self_assigning_variable
def
function
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,588
scope
ref
function
scope = node.scope()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,622
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,626
_check_redeclared_assign_name
def
function
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,627
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
1,638
_check_redeclared_assign_name
ref
function
self._check_redeclared_assign_name([element])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,645
most_common
ref
function
for name, count in names.most_common():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,647
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,651
check_messages
ref
function
@utils.check_messages("self-assigning-variable", "redeclared-assigned-name")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,652
visit_assign
def
function
def visit_assign(self, node: nodes.Assign) -> None: # Check *a, *b = ... assign_target = node.targets[0] # Check *a = b if isinstance(node.targets[0], nodes.Starred): self.add_message("invalid-star-assignment-target", node=node) if not isinstance(assign_target, nodes.Tuple): return if self._too_many_starred_for_tuple(assign_target): self.add_message("too-many-star-expressions", node=node) @utils.check_messages("star-needs-assignment-target") def visit_starred(self, node: nodes.Starred) -> None: """Check that a Starred expression is used in an assignment target.""" if isinstance(node.parent, nodes.Call): # f(*args) is converted to Call(args=[Starred]), so ignore # them for this check. return if isinstance(node.parent, (nodes.List, nodes.Tuple, nodes.Set, nodes.Dict)): # PEP 448 unpacking. return stmt = node.statement(future=_True) if not isinstance(stmt, nodes.Assign): return if stmt.value is node or stmt.value.parent_of(node): self.add_message("star-needs-assignment-target", node=node) @utils.check_messages( "init-is-generator", "return-in-init", "function-redefined", "return-arg-in-generator", "duplicate-argument-name", "nonlocal-and-global", "used-prior-global-declaration", ) def visit_functiondef(self, node: nodes.FunctionDef) -> None: self._check_nonlocal_and_global(node) self._check_name_used_prior_global(node) if not redefined_by_decorator( node ) and not utils.is_registered_in_singledispatch_function(node): self._check_redefinition(node.is_method() and "method" or "function", node) # checks for max returns, branch, return in __init__ returns = node.nodes_of_class( nodes.Return, skip_klass=(nodes.FunctionDef, nodes.ClassDef) ) if node.is_method() and node.name == "__init__": if node.is_generator(): self.add_message("init-is-generator", node=node) else: values = [r.value for r in returns] # Are we returning anything but None from constructors if any(v for v in values if not utils.is_none(v)): self.add_message("return-in-init", node=node) # Check for duplicate names by clustering args with same name for detailed report arg_clusters = collections.defaultdict(list) arguments: Iterator[Any] = filter(None, [node.args.args, node.args.kwonlyargs]) for arg in itertools.chain.from_iterable(arguments): arg_clusters[arg.name].append(arg) # provide detailed report about each repeated argument for argument_duplicates in arg_clusters.values(): if len(argument_duplicates) != 1: for argument in argument_duplicates: self.add_message( "duplicate-argument-name", line=argument.lineno, node=argument, args=(argument.name,), ) visit_asyncfunctiondef = visit_functiondef def _check_name_used_prior_global(self, node): scope_globals = { name: child for child in node.nodes_of_class(nodes.Global) for name in child.names if child.scope() is node } if not scope_globals: return for node_name in node.nodes_of_class(nodes.Name): if node_name.scope() is not node: continue name = node_name.name corresponding_global = scope_globals.get(name) if not corresponding_global: continue global_lineno = corresponding_global.fromlineno if global_lineno and global_lineno > node_name.fromlineno: self.add_message( "used-prior-global-declaration", node=node_name, args=(name,) ) def _check_nonlocal_and_global(self, node): """Check that a name is both nonlocal and global.""" def same_scope(current): return current.scope() is node from_iter = itertools.chain.from_iterable nonlocals = set( from_iter( child.names for child in node.nodes_of_class(nodes.Nonlocal) if same_scope(child) ) ) if not nonlocals: return global_vars = set( from_iter( child.names for child in node.nodes_of_class(nodes.Global) if same_scope(child) ) ) for name in nonlocals.intersection(global_vars): self.add_message("nonlocal-and-global", args=(name,), node=node) @utils.check_messages("return-outside-function") def visit_return(self, node: nodes.Return) -> None: if not isinstance(node.frame(future=_True), nodes.FunctionDef): self.add_message("return-outside-function", node=node) @utils.check_messages("yield-outside-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
1,653
_check_self_assigning_variable
ref
function
self._check_self_assigning_variable(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,654
_check_redeclared_assign_name
ref
function
self._check_redeclared_assign_name(node.targets)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,656
check_messages
ref
function
@utils.check_messages("redeclared-assigned-name")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,657
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
1,658
_check_redeclared_assign_name
ref
function
self._check_redeclared_assign_name([node.target])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,690
_create_naming_options
def
function
def _create_naming_options(): name_options = [] for name_type in sorted(KNOWN_NAME_TYPES): human_readable_name = constants.HUMAN_READABLE_TYPES[name_type] default_style = DEFAULT_NAMING_STYLES[name_type] name_type = name_type.replace("_", "-") name_options.append( ( f"{name_type}-naming-style", { "default": default_style, "type": "choice", "choices": list(NAMING_STYLES.keys()), "metavar": "<style>", "help": f"Naming style matching correct {human_readable_name} names.", }, ) ) name_options.append( ( f"{name_type}-rgx", { "default": None, "type": "regexp", "metavar": "<regexp>", "help": f"Regular expression matching correct {human_readable_name} names. Overrides {name_type}-naming-style.", }, ) ) return tuple(name_options)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,722
NameChecker
def
class
__init__ open _create_naming_rules visit_module leave_module visit_classdef visit_functiondef visit_global visit_assignname _recursive_check_names _find_name_group _raise_name_warning _name_allowed_by_regex _name_disallowed_by_regex _check_name _check_assign_to_new_keyword_violation _name_became_keyword_in_version
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,823
_create_naming_options
ref
function
) + _create_naming_options()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,838
reset_bad_names
ref
function
self.linter.stats.reset_bad_names()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,843
_create_naming_rules
ref
function
regexps, hints = self._create_naming_rules()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,853
_create_naming_rules
def
function
def _create_naming_rules(self): regexps = {} hints = {} for name_type in KNOWN_NAME_TYPES: naming_style_option_name = f"{name_type}_naming_style" naming_style_name = getattr(self.config, naming_style_option_name) regexps[name_type] = NAMING_STYLES[naming_style_name].get_regex(name_type) custom_regex_setting_name = f"{name_type}_rgx" custom_regex = getattr(self.config, custom_regex_setting_name, None) if custom_regex is not None: regexps[name_type] = custom_regex if custom_regex is not None: hints[name_type] = f"{custom_regex.pattern!r} pattern" else: hints[name_type] = f"{naming_style_name} naming style" return regexps, hints @utils.check_messages("disallowed-name", "invalid-name") def visit_module(self, node: nodes.Module) -> None: self._check_name("module", node.name.split(".")[-1], node) self._bad_names = {} def leave_module(self, _: nodes.Module) -> None: for all_groups in self._bad_names.values(): if len(all_groups) < 2: continue groups = collections.defaultdict(list) min_warnings = sys.maxsize prevalent_group, _ = max(all_groups.items(), key=lambda item: len(item[1])) for group in all_groups.values(): groups[len(group)].append(group) min_warnings = min(len(group), min_warnings) if len(groups[min_warnings]) > 1: by_line = sorted( groups[min_warnings], key=lambda group: min(warning[0].lineno for warning in group), ) warnings = itertools.chain(*by_line[1:]) else: warnings = groups[min_warnings][0] for args in warnings: self._raise_name_warning(prevalent_group, *args) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_classdef(self, node: nodes.ClassDef) -> None: self._check_assign_to_new_keyword_violation(node.name, node) self._check_name("class", node.name, node) for attr, anodes in node.instance_attrs.items(): if not any(node.instance_attr_ancestors(attr)): self._check_name("attr", attr, anodes[0]) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_functiondef(self, node: nodes.FunctionDef) -> None: # Do not emit any warnings if the method is just an implementation # of a base class method. self._check_assign_to_new_keyword_violation(node.name, node) confidence = interfaces.HIGH if node.is_method(): if utils.overrides_a_method(node.parent.frame(future=_True), node.name): return confidence = ( interfaces.INFERENCE if utils.has_known_bases(node.parent.frame(future=_True)) else interfaces.INFERENCE_FAILURE ) self._check_name( _determine_function_name_type(node, config=self.config), node.name, node, confidence, ) # Check argument names args = node.args.args if args is not None: self._recursive_check_names(args) visit_asyncfunctiondef = visit_functiondef @utils.check_messages("disallowed-name", "invalid-name") def visit_global(self, node: nodes.Global) -> None: for name in node.names: self._check_name("const", name, node) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_assignname(self, node: nodes.AssignName) -> None: """Check module level assigned names.""" self._check_assign_to_new_keyword_violation(node.name, node) frame = node.frame(future=_True) assign_type = node.assign_type() if isinstance(assign_type, nodes.Comprehension): self._check_name("inlinevar", node.name, node) elif isinstance(frame, nodes.Module): if isinstance(assign_type, nodes.Assign): if isinstance(utils.safe_infer(assign_type.value), nodes.ClassDef): self._check_name("class", node.name, node) # Don't emit if the name redefines an import # in an ImportError except handler. elif not _redefines_import(node) and isinstance( utils.safe_infer(assign_type.value), nodes.Const ): self._check_name("const", node.name, node) elif isinstance( assign_type, nodes.AnnAssign ) and utils.is_assign_name_annotated_with(node, "Final"): self._check_name("const", node.name, node) elif isinstance(frame, nodes.FunctionDef): # global introduced variable aren't in the function locals if node.name in frame and node.name not in frame.argnames(): if not _redefines_import(node): self._check_name("variable", node.name, node) elif isinstance(frame, nodes.ClassDef): if not list(frame.local_attr_ancestors(node.name)): for ancestor in frame.ancestors(): if ( ancestor.name == "Enum" and ancestor.root().name == "enum" or utils.is_assign_name_annotated_with(node, "Final") ): self._check_name("class_const", node.name, node) break else: self._check_name("class_attribute", node.name, node) def _recursive_check_names(self, args): """Check names in a possibly recursive list <arg>.""" for arg in args: if isinstance(arg, nodes.AssignName): self._check_name("argument", arg.name, arg) else: self._recursive_check_names(arg.elts) def _find_name_group(self, node_type): return self._name_group.get(node_type, node_type) def _raise_name_warning( self, prevalent_group: Optional[str], node: nodes.NodeNG, node_type: str, name: str, confidence, warning: str = "invalid-name", ) -> None: type_label = constants.HUMAN_READABLE_TYPES[node_type] hint = self._name_hints[node_type] if prevalent_group: # This happens in the multi naming match case. The expected # prevalent group needs to be spelled out to make the message # correct. hint = f"the `{prevalent_group}` group in the {hint}" if self.config.include_naming_hint: hint += f" ({self._name_regexps[node_type].pattern!r} pattern)" args = ( (type_label.capitalize(), name, hint) if warning == "invalid-name" else (type_label.capitalize(), name) ) self.add_message(warning, node=node, args=args, confidence=confidence) self.linter.stats.increase_bad_name(node_type, 1) def _name_allowed_by_regex(self, name: str) -> bool: return name in self.config.good_names or any( pattern.match(name) for pattern in self._good_names_rgxs_compiled ) def _name_disallowed_by_regex(self, name: str) -> bool: return name in self.config.bad_names or any( pattern.match(name) for pattern in self._bad_names_rgxs_compiled ) def _check_name(self, node_type, name, node, confidence=interfaces.HIGH): """Check for a name using the type's regexp.""" def _should_exempt_from_invalid_name(node): if node_type == "variable": inferred = utils.safe_infer(node) if isinstance(inferred, nodes.ClassDef): return _True return _False if self._name_allowed_by_regex(name=name): return if self._name_disallowed_by_regex(name=name): self.linter.stats.increase_bad_name(node_type, 1) self.add_message("disallowed-name", node=node, args=name) return regexp = self._name_regexps[node_type] match = regexp.match(name) if _is_multi_naming_match(match, node_type, confidence): name_group = self._find_name_group(node_type) bad_name_group = self._bad_names.setdefault(name_group, {}) warnings = bad_name_group.setdefault(match.lastgroup, []) warnings.append((node, node_type, name, confidence)) if match is None and not _should_exempt_from_invalid_name(node): self._raise_name_warning(None, node, node_type, name, confidence) def _check_assign_to_new_keyword_violation(self, name, node): keyword_first_version = self._name_became_keyword_in_version( name, self.KEYWORD_ONSET ) if keyword_first_version is not None: self.add_message( "assign-to-new-keyword", node=node, args=(name, keyword_first_version), confidence=interfaces.HIGH, ) @staticmethod def _name_became_keyword_in_version(name, rules): for version, keywords in rules.items(): if name in keywords and sys.version_info < version: return ".".join(str(v) for v in version) return None
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,861
get_regex
ref
function
regexps[name_type] = NAMING_STYLES[naming_style_name].get_regex(name_type)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,875
check_messages
ref
function
@utils.check_messages("disallowed-name", "invalid-name")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,876
visit_module
def
function
def visit_module(self, node: nodes.Module) -> None: self._check_name("module", node.name.split(".")[-1], node) self._bad_names = {} def leave_module(self, _: nodes.Module) -> None: for all_groups in self._bad_names.values(): if len(all_groups) < 2: continue groups = collections.defaultdict(list) min_warnings = sys.maxsize prevalent_group, _ = max(all_groups.items(), key=lambda item: len(item[1])) for group in all_groups.values(): groups[len(group)].append(group) min_warnings = min(len(group), min_warnings) if len(groups[min_warnings]) > 1: by_line = sorted( groups[min_warnings], key=lambda group: min(warning[0].lineno for warning in group), ) warnings = itertools.chain(*by_line[1:]) else: warnings = groups[min_warnings][0] for args in warnings: self._raise_name_warning(prevalent_group, *args) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_classdef(self, node: nodes.ClassDef) -> None: self._check_assign_to_new_keyword_violation(node.name, node) self._check_name("class", node.name, node) for attr, anodes in node.instance_attrs.items(): if not any(node.instance_attr_ancestors(attr)): self._check_name("attr", attr, anodes[0]) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_functiondef(self, node: nodes.FunctionDef) -> None: # Do not emit any warnings if the method is just an implementation # of a base class method. self._check_assign_to_new_keyword_violation(node.name, node) confidence = interfaces.HIGH if node.is_method(): if utils.overrides_a_method(node.parent.frame(future=_True), node.name): return confidence = ( interfaces.INFERENCE if utils.has_known_bases(node.parent.frame(future=_True)) else interfaces.INFERENCE_FAILURE ) self._check_name( _determine_function_name_type(node, config=self.config), node.name, node, confidence, ) # Check argument names args = node.args.args if args is not None: self._recursive_check_names(args) visit_asyncfunctiondef = visit_functiondef @utils.check_messages("disallowed-name", "invalid-name") def visit_global(self, node: nodes.Global) -> None: for name in node.names: self._check_name("const", name, node) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_assignname(self, node: nodes.AssignName) -> None: """Check module level assigned names.""" self._check_assign_to_new_keyword_violation(node.name, node) frame = node.frame(future=_True) assign_type = node.assign_type() if isinstance(assign_type, nodes.Comprehension): self._check_name("inlinevar", node.name, node) elif isinstance(frame, nodes.Module): if isinstance(assign_type, nodes.Assign): if isinstance(utils.safe_infer(assign_type.value), nodes.ClassDef): self._check_name("class", node.name, node) # Don't emit if the name redefines an import # in an ImportError except handler. elif not _redefines_import(node) and isinstance( utils.safe_infer(assign_type.value), nodes.Const ): self._check_name("const", node.name, node) elif isinstance( assign_type, nodes.AnnAssign ) and utils.is_assign_name_annotated_with(node, "Final"): self._check_name("const", node.name, node) elif isinstance(frame, nodes.FunctionDef): # global introduced variable aren't in the function locals if node.name in frame and node.name not in frame.argnames(): if not _redefines_import(node): self._check_name("variable", node.name, node) elif isinstance(frame, nodes.ClassDef): if not list(frame.local_attr_ancestors(node.name)): for ancestor in frame.ancestors(): if ( ancestor.name == "Enum" and ancestor.root().name == "enum" or utils.is_assign_name_annotated_with(node, "Final") ): self._check_name("class_const", node.name, node) break else: self._check_name("class_attribute", node.name, node) def _recursive_check_names(self, args): """Check names in a possibly recursive list <arg>.""" for arg in args: if isinstance(arg, nodes.AssignName): self._check_name("argument", arg.name, arg) else: self._recursive_check_names(arg.elts) def _find_name_group(self, node_type): return self._name_group.get(node_type, node_type) def _raise_name_warning( self, prevalent_group: Optional[str], node: nodes.NodeNG, node_type: str, name: str, confidence, warning: str = "invalid-name", ) -> None: type_label = constants.HUMAN_READABLE_TYPES[node_type] hint = self._name_hints[node_type] if prevalent_group: # This happens in the multi naming match case. The expected # prevalent group needs to be spelled out to make the message # correct. hint = f"the `{prevalent_group}` group in the {hint}" if self.config.include_naming_hint: hint += f" ({self._name_regexps[node_type].pattern!r} pattern)" args = ( (type_label.capitalize(), name, hint) if warning == "invalid-name" else (type_label.capitalize(), name) ) self.add_message(warning, node=node, args=args, confidence=confidence) self.linter.stats.increase_bad_name(node_type, 1) def _name_allowed_by_regex(self, name: str) -> bool: return name in self.config.good_names or any( pattern.match(name) for pattern in self._good_names_rgxs_compiled ) def _name_disallowed_by_regex(self, name: str) -> bool: return name in self.config.bad_names or any( pattern.match(name) for pattern in self._bad_names_rgxs_compiled ) def _check_name(self, node_type, name, node, confidence=interfaces.HIGH): """Check for a name using the type's regexp.""" def _should_exempt_from_invalid_name(node): if node_type == "variable": inferred = utils.safe_infer(node) if isinstance(inferred, nodes.ClassDef): return _True return _False if self._name_allowed_by_regex(name=name): return if self._name_disallowed_by_regex(name=name): self.linter.stats.increase_bad_name(node_type, 1) self.add_message("disallowed-name", node=node, args=name) return regexp = self._name_regexps[node_type] match = regexp.match(name) if _is_multi_naming_match(match, node_type, confidence): name_group = self._find_name_group(node_type) bad_name_group = self._bad_names.setdefault(name_group, {}) warnings = bad_name_group.setdefault(match.lastgroup, []) warnings.append((node, node_type, name, confidence)) if match is None and not _should_exempt_from_invalid_name(node): self._raise_name_warning(None, node, node_type, name, confidence) def _check_assign_to_new_keyword_violation(self, name, node): keyword_first_version = self._name_became_keyword_in_version( name, self.KEYWORD_ONSET ) if keyword_first_version is not None: self.add_message( "assign-to-new-keyword", node=node, args=(name, keyword_first_version), confidence=interfaces.HIGH, ) @staticmethod def _name_became_keyword_in_version(name, rules): for version, keywords in rules.items(): if name in keywords and sys.version_info < version: return ".".join(str(v) for v in version) return None
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,877
_check_name
ref
function
self._check_name("module", node.name.split(".")[-1], node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
1,880
leave_module
def
function
def leave_module(self, _: nodes.Module) -> None: for all_groups in self._bad_names.values(): if len(all_groups) < 2: continue groups = collections.defaultdict(list) min_warnings = sys.maxsize prevalent_group, _ = max(all_groups.items(), key=lambda item: len(item[1])) for group in all_groups.values(): groups[len(group)].append(group) min_warnings = min(len(group), min_warnings) if len(groups[min_warnings]) > 1: by_line = sorted( groups[min_warnings], key=lambda group: min(warning[0].lineno for warning in group), ) warnings = itertools.chain(*by_line[1:]) else: warnings = groups[min_warnings][0] for args in warnings: self._raise_name_warning(prevalent_group, *args) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_classdef(self, node: nodes.ClassDef) -> None: self._check_assign_to_new_keyword_violation(node.name, node) self._check_name("class", node.name, node) for attr, anodes in node.instance_attrs.items(): if not any(node.instance_attr_ancestors(attr)): self._check_name("attr", attr, anodes[0]) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_functiondef(self, node: nodes.FunctionDef) -> None: # Do not emit any warnings if the method is just an implementation # of a base class method. self._check_assign_to_new_keyword_violation(node.name, node) confidence = interfaces.HIGH if node.is_method(): if utils.overrides_a_method(node.parent.frame(future=_True), node.name): return confidence = ( interfaces.INFERENCE if utils.has_known_bases(node.parent.frame(future=_True)) else interfaces.INFERENCE_FAILURE ) self._check_name( _determine_function_name_type(node, config=self.config), node.name, node, confidence, ) # Check argument names args = node.args.args if args is not None: self._recursive_check_names(args) visit_asyncfunctiondef = visit_functiondef @utils.check_messages("disallowed-name", "invalid-name") def visit_global(self, node: nodes.Global) -> None: for name in node.names: self._check_name("const", name, node) @utils.check_messages("disallowed-name", "invalid-name", "assign-to-new-keyword") def visit_assignname(self, node: nodes.AssignName) -> None: """Check module level assigned names.""" self._check_assign_to_new_keyword_violation(node.name, node) frame = node.frame(future=_True) assign_type = node.assign_type() if isinstance(assign_type, nodes.Comprehension): self._check_name("inlinevar", node.name, node) elif isinstance(frame, nodes.Module): if isinstance(assign_type, nodes.Assign): if isinstance(utils.safe_infer(assign_type.value), nodes.ClassDef): self._check_name("class", node.name, node) # Don't emit if the name redefines an import # in an ImportError except handler. elif not _redefines_import(node) and isinstance( utils.safe_infer(assign_type.value), nodes.Const ): self._check_name("const", node.name, node) elif isinstance( assign_type, nodes.AnnAssign ) and utils.is_assign_name_annotated_with(node, "Final"): self._check_name("const", node.name, node) elif isinstance(frame, nodes.FunctionDef): # global introduced variable aren't in the function locals if node.name in frame and node.name not in frame.argnames(): if not _redefines_import(node): self._check_name("variable", node.name, node) elif isinstance(frame, nodes.ClassDef): if not list(frame.local_attr_ancestors(node.name)): for ancestor in frame.ancestors(): if ( ancestor.name == "Enum" and ancestor.root().name == "enum" or utils.is_assign_name_annotated_with(node, "Final") ): self._check_name("class_const", node.name, node) break else: self._check_name("class_attribute", node.name, node) def _recursive_check_names(self, args): """Check names in a possibly recursive list <arg>.""" for arg in args: if isinstance(arg, nodes.AssignName): self._check_name("argument", arg.name, arg) else: self._recursive_check_names(arg.elts) def _find_name_group(self, node_type): return self._name_group.get(node_type, node_type) def _raise_name_warning( self, prevalent_group: Optional[str], node: nodes.NodeNG, node_type: str, name: str, confidence, warning: str = "invalid-name", ) -> None: type_label = constants.HUMAN_READABLE_TYPES[node_type] hint = self._name_hints[node_type] if prevalent_group: # This happens in the multi naming match case. The expected # prevalent group needs to be spelled out to make the message # correct. hint = f"the `{prevalent_group}` group in the {hint}" if self.config.include_naming_hint: hint += f" ({self._name_regexps[node_type].pattern!r} pattern)" args = ( (type_label.capitalize(), name, hint) if warning == "invalid-name" else (type_label.capitalize(), name) ) self.add_message(warning, node=node, args=args, confidence=confidence) self.linter.stats.increase_bad_name(node_type, 1) def _name_allowed_by_regex(self, name: str) -> bool: return name in self.config.good_names or any( pattern.match(name) for pattern in self._good_names_rgxs_compiled ) def _name_disallowed_by_regex(self, name: str) -> bool: return name in self.config.bad_names or any( pattern.match(name) for pattern in self._bad_names_rgxs_compiled ) def _check_name(self, node_type, name, node, confidence=interfaces.HIGH): """Check for a name using the type's regexp.""" def _should_exempt_from_invalid_name(node): if node_type == "variable": inferred = utils.safe_infer(node) if isinstance(inferred, nodes.ClassDef): return _True return _False if self._name_allowed_by_regex(name=name): return if self._name_disallowed_by_regex(name=name): self.linter.stats.increase_bad_name(node_type, 1) self.add_message("disallowed-name", node=node, args=name) return regexp = self._name_regexps[node_type] match = regexp.match(name) if _is_multi_naming_match(match, node_type, confidence): name_group = self._find_name_group(node_type) bad_name_group = self._bad_names.setdefault(name_group, {}) warnings = bad_name_group.setdefault(match.lastgroup, []) warnings.append((node, node_type, name, confidence)) if match is None and not _should_exempt_from_invalid_name(node): self._raise_name_warning(None, node, node_type, name, confidence) def _check_assign_to_new_keyword_violation(self, name, node): keyword_first_version = self._name_became_keyword_in_version( name, self.KEYWORD_ONSET ) if keyword_first_version is not None: self.add_message( "assign-to-new-keyword", node=node, args=(name, keyword_first_version), confidence=interfaces.HIGH, ) @staticmethod def _name_became_keyword_in_version(name, rules): for version, keywords in rules.items(): if name in keywords and sys.version_info < version: return ".".join(str(v) for v in version) return None