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/typecheck.py
pylint/checkers/typecheck.py
995
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
996
_metaclass_name
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
999
visit_assignattr
def
function
def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance(node.assign_type(), nodes.AugAssign): self.visit_attribute(node) def visit_delattr(self, node: nodes.DelAttr) -> None: self.visit_attribute(node) @check_messages("no-member", "c-extension-no-member") def visit_attribute(self, node: nodes.Attribute) -> None: """Check that the accessed attribute exists. to avoid too much false positives for now, we'll consider the code as correct if a single of the inferred nodes has the accessed attribute. function/method, super call and metaclasses are ignored """ if any( pattern.match(name) for name in (node.attrname, node.as_string()) for pattern in self._compiled_generated_members ): return try: inferred = list(node.expr.infer()) except astroid.InferenceError: return # list of (node, nodename) which are missing the attribute missingattr = set() non_opaque_inference_results = [ owner for owner in inferred if owner is not astroid.Uninferable and not isinstance(owner, nodes.Unknown) ] if ( len(non_opaque_inference_results) != len(inferred) and self.config.ignore_on_opaque_inference ): # There is an ambiguity in the inference. Since we can't # make sure that we won't emit a false positive, we just stop # whenever the inference returns an opaque inference object. return for owner in non_opaque_inference_results: name = getattr(owner, "name", None) if _is_owner_ignored( owner, name, self.config.ignored_classes, self.config.ignored_modules ): continue qualname = f"{owner.pytype()}.{node.attrname}" if any( pattern.match(qualname) for pattern in self._compiled_generated_members ): return try: if not [ n for n in owner.getattr(node.attrname) if not isinstance(n.statement(future=_True), nodes.AugAssign) ]: missingattr.add((owner, name)) continue except astroid.exceptions.StatementMissing: continue except AttributeError: continue except astroid.DuplicateBasesError: continue except astroid.NotFoundError: # This can't be moved before the actual .getattr call, # because there can be more values inferred and we are # stopping after the first one which has the attribute in question. # The problem is that if the first one has the attribute, # but we continue to the next values which doesn't have the # attribute, then we'll have a false positive. # So call this only after the call has been made. if not _emit_no_member( node, owner, name, self._mixin_class_rgx, ignored_mixins=self.config.ignore_mixin_members, ignored_none=self.config.ignore_none, ): continue missingattr.add((owner, name)) continue # stop on the first found break else: # we have not found any node with the attributes, display the # message for inferred nodes done = set() for owner, name in missingattr: if isinstance(owner, astroid.Instance): actual = owner._proxied else: actual = owner if actual in done: continue done.add(actual) msg, hint = self._get_nomember_msgid_hint(node, owner) self.add_message( msg, node=node, args=(owner.display_type(), name, node.attrname, hint), confidence=INFERENCE, ) def _get_nomember_msgid_hint(self, node, owner): suggestions_are_possible = self._suggestion_mode and isinstance( owner, nodes.Module ) if suggestions_are_possible and _is_c_extension(owner): msg = "c-extension-no-member" hint = "" else: msg = "no-member" if self.config.missing_member_hint: hint = _missing_member_hint( owner, node.attrname, self.config.missing_member_hint_distance, self.config.missing_member_max_choices, ) else: hint = "" return msg, hint @check_messages( "assignment-from-no-return", "assignment-from-none", "non-str-assignment-to-dunder-name", ) def visit_assign(self, node: nodes.Assign) -> None: """Process assignments in the AST.""" self._check_assignment_from_function_call(node) self._check_dundername_is_string(node) def _check_assignment_from_function_call(self, node: nodes.Assign) -> None: """When assigning to a function call, check that the function returns a valid value.""" if not isinstance(node.value, nodes.Call): return function_node = safe_infer(node.value.func) funcs = (nodes.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod) if not isinstance(function_node, funcs): return # Unwrap to get the actual function node object if isinstance(function_node, astroid.BoundMethod) and isinstance( function_node._proxied, astroid.UnboundMethod ): function_node = function_node._proxied._proxied # Make sure that it's a valid function that we can analyze. # Ordered from less expensive to more expensive checks. if ( not function_node.is_function or function_node.decorators or self._is_ignored_function(function_node) ): return # Fix a false-negative for list.sort(), see issue #5722 if self._is_list_sort_method(node.value): self.add_message("assignment-from-none", node=node, confidence=INFERENCE) return if not function_node.root().fully_defined(): return return_nodes = list( function_node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef) ) if not return_nodes: self.add_message("assignment-from-no-return", node=node) else: for ret_node in return_nodes: if not ( isinstance(ret_node.value, nodes.Const) and ret_node.value.value is None or ret_node.value is None ): break else: self.add_message("assignment-from-none", node=node) @staticmethod def _is_ignored_function( function_node: Union[nodes.FunctionDef, bases.UnboundMethod] ) -> bool: return ( isinstance(function_node, nodes.AsyncFunctionDef) or utils.is_error(function_node) or function_node.is_generator() or function_node.is_abstract(pass_is_abstract=_False) ) @staticmethod def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,000
assign_type
ref
function
if isinstance(node.assign_type(), nodes.AugAssign):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,001
visit_attribute
ref
function
self.visit_attribute(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,003
visit_delattr
def
function
def visit_delattr(self, node: nodes.DelAttr) -> None: self.visit_attribute(node) @check_messages("no-member", "c-extension-no-member") def visit_attribute(self, node: nodes.Attribute) -> None: """Check that the accessed attribute exists. to avoid too much false positives for now, we'll consider the code as correct if a single of the inferred nodes has the accessed attribute. function/method, super call and metaclasses are ignored """ if any( pattern.match(name) for name in (node.attrname, node.as_string()) for pattern in self._compiled_generated_members ): return try: inferred = list(node.expr.infer()) except astroid.InferenceError: return # list of (node, nodename) which are missing the attribute missingattr = set() non_opaque_inference_results = [ owner for owner in inferred if owner is not astroid.Uninferable and not isinstance(owner, nodes.Unknown) ] if ( len(non_opaque_inference_results) != len(inferred) and self.config.ignore_on_opaque_inference ): # There is an ambiguity in the inference. Since we can't # make sure that we won't emit a false positive, we just stop # whenever the inference returns an opaque inference object. return for owner in non_opaque_inference_results: name = getattr(owner, "name", None) if _is_owner_ignored( owner, name, self.config.ignored_classes, self.config.ignored_modules ): continue qualname = f"{owner.pytype()}.{node.attrname}" if any( pattern.match(qualname) for pattern in self._compiled_generated_members ): return try: if not [ n for n in owner.getattr(node.attrname) if not isinstance(n.statement(future=_True), nodes.AugAssign) ]: missingattr.add((owner, name)) continue except astroid.exceptions.StatementMissing: continue except AttributeError: continue except astroid.DuplicateBasesError: continue except astroid.NotFoundError: # This can't be moved before the actual .getattr call, # because there can be more values inferred and we are # stopping after the first one which has the attribute in question. # The problem is that if the first one has the attribute, # but we continue to the next values which doesn't have the # attribute, then we'll have a false positive. # So call this only after the call has been made. if not _emit_no_member( node, owner, name, self._mixin_class_rgx, ignored_mixins=self.config.ignore_mixin_members, ignored_none=self.config.ignore_none, ): continue missingattr.add((owner, name)) continue # stop on the first found break else: # we have not found any node with the attributes, display the # message for inferred nodes done = set() for owner, name in missingattr: if isinstance(owner, astroid.Instance): actual = owner._proxied else: actual = owner if actual in done: continue done.add(actual) msg, hint = self._get_nomember_msgid_hint(node, owner) self.add_message( msg, node=node, args=(owner.display_type(), name, node.attrname, hint), confidence=INFERENCE, ) def _get_nomember_msgid_hint(self, node, owner): suggestions_are_possible = self._suggestion_mode and isinstance( owner, nodes.Module ) if suggestions_are_possible and _is_c_extension(owner): msg = "c-extension-no-member" hint = "" else: msg = "no-member" if self.config.missing_member_hint: hint = _missing_member_hint( owner, node.attrname, self.config.missing_member_hint_distance, self.config.missing_member_max_choices, ) else: hint = "" return msg, hint @check_messages( "assignment-from-no-return", "assignment-from-none", "non-str-assignment-to-dunder-name", ) def visit_assign(self, node: nodes.Assign) -> None: """Process assignments in the AST.""" self._check_assignment_from_function_call(node) self._check_dundername_is_string(node) def _check_assignment_from_function_call(self, node: nodes.Assign) -> None: """When assigning to a function call, check that the function returns a valid value.""" if not isinstance(node.value, nodes.Call): return function_node = safe_infer(node.value.func) funcs = (nodes.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod) if not isinstance(function_node, funcs): return # Unwrap to get the actual function node object if isinstance(function_node, astroid.BoundMethod) and isinstance( function_node._proxied, astroid.UnboundMethod ): function_node = function_node._proxied._proxied # Make sure that it's a valid function that we can analyze. # Ordered from less expensive to more expensive checks. if ( not function_node.is_function or function_node.decorators or self._is_ignored_function(function_node) ): return # Fix a false-negative for list.sort(), see issue #5722 if self._is_list_sort_method(node.value): self.add_message("assignment-from-none", node=node, confidence=INFERENCE) return if not function_node.root().fully_defined(): return return_nodes = list( function_node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef) ) if not return_nodes: self.add_message("assignment-from-no-return", node=node) else: for ret_node in return_nodes: if not ( isinstance(ret_node.value, nodes.Const) and ret_node.value.value is None or ret_node.value is None ): break else: self.add_message("assignment-from-none", node=node) @staticmethod def _is_ignored_function( function_node: Union[nodes.FunctionDef, bases.UnboundMethod] ) -> bool: return ( isinstance(function_node, nodes.AsyncFunctionDef) or utils.is_error(function_node) or function_node.is_generator() or function_node.is_abstract(pass_is_abstract=_False) ) @staticmethod def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,004
visit_attribute
ref
function
self.visit_attribute(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,006
check_messages
ref
function
@check_messages("no-member", "c-extension-no-member")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,007
visit_attribute
def
function
def visit_attribute(self, node: nodes.Attribute) -> None: """Check that the accessed attribute exists. to avoid too much false positives for now, we'll consider the code as correct if a single of the inferred nodes has the accessed attribute. function/method, super call and metaclasses are ignored """ if any( pattern.match(name) for name in (node.attrname, node.as_string()) for pattern in self._compiled_generated_members ): return try: inferred = list(node.expr.infer()) except astroid.InferenceError: return # list of (node, nodename) which are missing the attribute missingattr = set() non_opaque_inference_results = [ owner for owner in inferred if owner is not astroid.Uninferable and not isinstance(owner, nodes.Unknown) ] if ( len(non_opaque_inference_results) != len(inferred) and self.config.ignore_on_opaque_inference ): # There is an ambiguity in the inference. Since we can't # make sure that we won't emit a false positive, we just stop # whenever the inference returns an opaque inference object. return for owner in non_opaque_inference_results: name = getattr(owner, "name", None) if _is_owner_ignored( owner, name, self.config.ignored_classes, self.config.ignored_modules ): continue qualname = f"{owner.pytype()}.{node.attrname}" if any( pattern.match(qualname) for pattern in self._compiled_generated_members ): return try: if not [ n for n in owner.getattr(node.attrname) if not isinstance(n.statement(future=_True), nodes.AugAssign) ]: missingattr.add((owner, name)) continue except astroid.exceptions.StatementMissing: continue except AttributeError: continue except astroid.DuplicateBasesError: continue except astroid.NotFoundError: # This can't be moved before the actual .getattr call, # because there can be more values inferred and we are # stopping after the first one which has the attribute in question. # The problem is that if the first one has the attribute, # but we continue to the next values which doesn't have the # attribute, then we'll have a false positive. # So call this only after the call has been made. if not _emit_no_member( node, owner, name, self._mixin_class_rgx, ignored_mixins=self.config.ignore_mixin_members, ignored_none=self.config.ignore_none, ): continue missingattr.add((owner, name)) continue # stop on the first found break else: # we have not found any node with the attributes, display the # message for inferred nodes done = set() for owner, name in missingattr: if isinstance(owner, astroid.Instance): actual = owner._proxied else: actual = owner if actual in done: continue done.add(actual) msg, hint = self._get_nomember_msgid_hint(node, owner) self.add_message( msg, node=node, args=(owner.display_type(), name, node.attrname, hint), confidence=INFERENCE, ) def _get_nomember_msgid_hint(self, node, owner): suggestions_are_possible = self._suggestion_mode and isinstance( owner, nodes.Module ) if suggestions_are_possible and _is_c_extension(owner): msg = "c-extension-no-member" hint = "" else: msg = "no-member" if self.config.missing_member_hint: hint = _missing_member_hint( owner, node.attrname, self.config.missing_member_hint_distance, self.config.missing_member_max_choices, ) else: hint = "" return msg, hint @check_messages( "assignment-from-no-return", "assignment-from-none", "non-str-assignment-to-dunder-name", ) def visit_assign(self, node: nodes.Assign) -> None: """Process assignments in the AST.""" self._check_assignment_from_function_call(node) self._check_dundername_is_string(node) def _check_assignment_from_function_call(self, node: nodes.Assign) -> None: """When assigning to a function call, check that the function returns a valid value.""" if not isinstance(node.value, nodes.Call): return function_node = safe_infer(node.value.func) funcs = (nodes.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod) if not isinstance(function_node, funcs): return # Unwrap to get the actual function node object if isinstance(function_node, astroid.BoundMethod) and isinstance( function_node._proxied, astroid.UnboundMethod ): function_node = function_node._proxied._proxied # Make sure that it's a valid function that we can analyze. # Ordered from less expensive to more expensive checks. if ( not function_node.is_function or function_node.decorators or self._is_ignored_function(function_node) ): return # Fix a false-negative for list.sort(), see issue #5722 if self._is_list_sort_method(node.value): self.add_message("assignment-from-none", node=node, confidence=INFERENCE) return if not function_node.root().fully_defined(): return return_nodes = list( function_node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef) ) if not return_nodes: self.add_message("assignment-from-no-return", node=node) else: for ret_node in return_nodes: if not ( isinstance(ret_node.value, nodes.Const) and ret_node.value.value is None or ret_node.value is None ): break else: self.add_message("assignment-from-none", node=node) @staticmethod def _is_ignored_function( function_node: Union[nodes.FunctionDef, bases.UnboundMethod] ) -> bool: return ( isinstance(function_node, nodes.AsyncFunctionDef) or utils.is_error(function_node) or function_node.is_generator() or function_node.is_abstract(pass_is_abstract=_False) ) @staticmethod def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,017
as_string
ref
function
for name in (node.attrname, node.as_string())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,023
infer
ref
function
inferred = list(node.expr.infer())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,045
_is_owner_ignored
ref
function
if _is_owner_ignored(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,050
pytype
ref
function
qualname = f"{owner.pytype()}.{node.attrname}"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,060
statement
ref
function
if not isinstance(n.statement(future=True), nodes.AugAssign)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,078
_emit_no_member
ref
function
if not _emit_no_member(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,104
_get_nomember_msgid_hint
ref
function
msg, hint = self._get_nomember_msgid_hint(node, owner)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,105
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,108
display_type
ref
function
args=(owner.display_type(), name, node.attrname, hint),
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,112
_get_nomember_msgid_hint
def
function
def _get_nomember_msgid_hint(self, node, owner): suggestions_are_possible = self._suggestion_mode and isinstance( owner, nodes.Module ) if suggestions_are_possible and _is_c_extension(owner): msg = "c-extension-no-member" hint = "" else: msg = "no-member" if self.config.missing_member_hint: hint = _missing_member_hint( owner, node.attrname, self.config.missing_member_hint_distance, self.config.missing_member_max_choices, ) else: hint = "" return msg, hint @check_messages( "assignment-from-no-return", "assignment-from-none", "non-str-assignment-to-dunder-name", ) def visit_assign(self, node: nodes.Assign) -> None: """Process assignments in the AST.""" self._check_assignment_from_function_call(node) self._check_dundername_is_string(node) def _check_assignment_from_function_call(self, node: nodes.Assign) -> None: """When assigning to a function call, check that the function returns a valid value.""" if not isinstance(node.value, nodes.Call): return function_node = safe_infer(node.value.func) funcs = (nodes.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod) if not isinstance(function_node, funcs): return # Unwrap to get the actual function node object if isinstance(function_node, astroid.BoundMethod) and isinstance( function_node._proxied, astroid.UnboundMethod ): function_node = function_node._proxied._proxied # Make sure that it's a valid function that we can analyze. # Ordered from less expensive to more expensive checks. if ( not function_node.is_function or function_node.decorators or self._is_ignored_function(function_node) ): return # Fix a false-negative for list.sort(), see issue #5722 if self._is_list_sort_method(node.value): self.add_message("assignment-from-none", node=node, confidence=INFERENCE) return if not function_node.root().fully_defined(): return return_nodes = list( function_node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef) ) if not return_nodes: self.add_message("assignment-from-no-return", node=node) else: for ret_node in return_nodes: if not ( isinstance(ret_node.value, nodes.Const) and ret_node.value.value is None or ret_node.value is None ): break else: self.add_message("assignment-from-none", node=node) @staticmethod def _is_ignored_function( function_node: Union[nodes.FunctionDef, bases.UnboundMethod] ) -> bool: return ( isinstance(function_node, nodes.AsyncFunctionDef) or utils.is_error(function_node) or function_node.is_generator() or function_node.is_abstract(pass_is_abstract=_False) ) @staticmethod def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,116
_is_c_extension
ref
function
if suggestions_are_possible and _is_c_extension(owner):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,122
_missing_member_hint
ref
function
hint = _missing_member_hint(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,132
check_messages
ref
function
@check_messages(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,137
visit_assign
def
function
def visit_assign(self, node: nodes.Assign) -> None: """Process assignments in the AST.""" self._check_assignment_from_function_call(node) self._check_dundername_is_string(node) def _check_assignment_from_function_call(self, node: nodes.Assign) -> None: """When assigning to a function call, check that the function returns a valid value.""" if not isinstance(node.value, nodes.Call): return function_node = safe_infer(node.value.func) funcs = (nodes.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod) if not isinstance(function_node, funcs): return # Unwrap to get the actual function node object if isinstance(function_node, astroid.BoundMethod) and isinstance( function_node._proxied, astroid.UnboundMethod ): function_node = function_node._proxied._proxied # Make sure that it's a valid function that we can analyze. # Ordered from less expensive to more expensive checks. if ( not function_node.is_function or function_node.decorators or self._is_ignored_function(function_node) ): return # Fix a false-negative for list.sort(), see issue #5722 if self._is_list_sort_method(node.value): self.add_message("assignment-from-none", node=node, confidence=INFERENCE) return if not function_node.root().fully_defined(): return return_nodes = list( function_node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef) ) if not return_nodes: self.add_message("assignment-from-no-return", node=node) else: for ret_node in return_nodes: if not ( isinstance(ret_node.value, nodes.Const) and ret_node.value.value is None or ret_node.value is None ): break else: self.add_message("assignment-from-none", node=node) @staticmethod def _is_ignored_function( function_node: Union[nodes.FunctionDef, bases.UnboundMethod] ) -> bool: return ( isinstance(function_node, nodes.AsyncFunctionDef) or utils.is_error(function_node) or function_node.is_generator() or function_node.is_abstract(pass_is_abstract=_False) ) @staticmethod def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,140
_check_assignment_from_function_call
ref
function
self._check_assignment_from_function_call(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,141
_check_dundername_is_string
ref
function
self._check_dundername_is_string(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,143
_check_assignment_from_function_call
def
function
def _check_assignment_from_function_call(self, node: nodes.Assign) -> None: """When assigning to a function call, check that the function returns a valid value.""" if not isinstance(node.value, nodes.Call): return function_node = safe_infer(node.value.func) funcs = (nodes.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod) if not isinstance(function_node, funcs): return # Unwrap to get the actual function node object if isinstance(function_node, astroid.BoundMethod) and isinstance( function_node._proxied, astroid.UnboundMethod ): function_node = function_node._proxied._proxied # Make sure that it's a valid function that we can analyze. # Ordered from less expensive to more expensive checks. if ( not function_node.is_function or function_node.decorators or self._is_ignored_function(function_node) ): return # Fix a false-negative for list.sort(), see issue #5722 if self._is_list_sort_method(node.value): self.add_message("assignment-from-none", node=node, confidence=INFERENCE) return if not function_node.root().fully_defined(): return return_nodes = list( function_node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef) ) if not return_nodes: self.add_message("assignment-from-no-return", node=node) else: for ret_node in return_nodes: if not ( isinstance(ret_node.value, nodes.Const) and ret_node.value.value is None or ret_node.value is None ): break else: self.add_message("assignment-from-none", node=node) @staticmethod def _is_ignored_function( function_node: Union[nodes.FunctionDef, bases.UnboundMethod] ) -> bool: return ( isinstance(function_node, nodes.AsyncFunctionDef) or utils.is_error(function_node) or function_node.is_generator() or function_node.is_abstract(pass_is_abstract=_False) ) @staticmethod def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,148
safe_infer
ref
function
function_node = safe_infer(node.value.func)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,164
_is_ignored_function
ref
function
or self._is_ignored_function(function_node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,169
_is_list_sort_method
ref
function
if self._is_list_sort_method(node.value):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,170
add_message
ref
function
self.add_message("assignment-from-none", node=node, confidence=INFERENCE)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,173
root
ref
function
if not function_node.root().fully_defined():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,173
fully_defined
ref
function
if not function_node.root().fully_defined():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,177
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,180
add_message
ref
function
self.add_message("assignment-from-no-return", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,190
add_message
ref
function
self.add_message("assignment-from-none", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,193
_is_ignored_function
def
function
def _is_ignored_function( function_node: Union[nodes.FunctionDef, bases.UnboundMethod] ) -> bool: return ( isinstance(function_node, nodes.AsyncFunctionDef) or utils.is_error(function_node) or function_node.is_generator() or function_node.is_abstract(pass_is_abstract=_False) ) @staticmethod def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,198
is_error
ref
function
or utils.is_error(function_node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,199
is_generator
ref
function
or function_node.is_generator()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,200
is_abstract
ref
function
or function_node.is_abstract(pass_is_abstract=False)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,204
_is_list_sort_method
def
function
def _is_list_sort_method(node: nodes.Call) -> bool: return ( isinstance(node.func, nodes.Attribute) and node.func.attrname == "sort" and isinstance(utils.safe_infer(node.func.expr), nodes.List) ) def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,208
safe_infer
ref
function
and isinstance(utils.safe_infer(node.func.expr), nodes.List)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,211
_check_dundername_is_string
def
function
def _check_dundername_is_string(self, node) -> None: """Check a string is assigned to self.__name__.""" # Check the left-hand side of the assignment is <something>.__name__ lhs = node.targets[0] if not isinstance(lhs, nodes.AssignAttr): return if not lhs.attrname == "__name__": return # If the right-hand side is not a string rhs = node.value if isinstance(rhs, nodes.Const) and isinstance(rhs.value, str): return inferred = utils.safe_infer(rhs) if not inferred: return if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)): # Add the message self.add_message("non-str-assignment-to-dunder-name", node=node) def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,225
safe_infer
ref
function
inferred = utils.safe_infer(rhs)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,230
add_message
ref
function
self.add_message("non-str-assignment-to-dunder-name", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,232
_check_uninferable_call
def
function
def _check_uninferable_call(self, node): """Check that the given uninferable Call node does not call an actual function. """ if not isinstance(node.func, nodes.Attribute): return # Look for properties. First, obtain # the lhs of the Attribute node and search the attribute # there. If that attribute is a property or a subclass of properties, # then most likely it's not callable. expr = node.func.expr klass = safe_infer(expr) if ( klass is None or klass is astroid.Uninferable or not isinstance(klass, astroid.Instance) ): return try: attrs = klass._proxied.getattr(node.func.attrname) except astroid.NotFoundError: return for attr in attrs: if attr is astroid.Uninferable: continue if not isinstance(attr, nodes.FunctionDef): continue # Decorated, see if it is decorated with a property. # Also, check the returns and see if they are callable. if decorated_with_property(attr): try: all_returns_are_callable = all( return_node.callable() or return_node is astroid.Uninferable for return_node in attr.infer_call_result(node) ) except astroid.InferenceError: continue if not all_returns_are_callable: self.add_message( "not-callable", node=node, args=node.func.as_string() ) break def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,245
safe_infer
ref
function
klass = safe_infer(expr)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,266
decorated_with_property
ref
function
if decorated_with_property(attr):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,271
infer_call_result
ref
function
for return_node in attr.infer_call_result(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,277
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,278
as_string
ref
function
"not-callable", node=node, args=node.func.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,282
_check_argument_order
def
function
def _check_argument_order(self, node, call_site, called, called_param_names): """Match the supplied argument names against the function parameters. Warn if some argument names are not in the same order as they are in the function signature. """ # Check for called function being an object instance function # If so, ignore the initial 'self' argument in the signature try: is_classdef = isinstance(called.parent, nodes.ClassDef) if is_classdef and called_param_names[0] == "self": called_param_names = called_param_names[1:] except IndexError: return try: # extract argument names, if they have names calling_parg_names = [p.name for p in call_site.positional_arguments] # Additionally, get names of keyword arguments to use in a full match # against parameters calling_kwarg_names = [ arg.name for arg in call_site.keyword_arguments.values() ] except AttributeError: # the type of arg does not provide a `.name`. In this case we # stop checking for out-of-order arguments because it is only relevant # for named variables. return # Don't check for ordering if there is an unmatched arg or param arg_set = set(calling_parg_names) | set(calling_kwarg_names) param_set = set(called_param_names) if arg_set != param_set: return # Warn based on the equality of argument ordering if calling_parg_names != called_param_names[: len(calling_parg_names)]: self.add_message("arguments-out-of-order", node=node, args=()) def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,319
add_message
ref
function
self.add_message("arguments-out-of-order", node=node, args=())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,321
_check_isinstance_args
def
function
def _check_isinstance_args(self, node): if len(node.args) != 2: # isinstance called with wrong number of args return second_arg = node.args[1] if _is_invalid_isinstance_type(second_arg): self.add_message("isinstance-second-argument-not-valid-type", node=node) # pylint: disable=too-many-branches,too-many-locals @check_messages(*(list(MSGS.keys()))) def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,327
_is_invalid_isinstance_type
ref
function
if _is_invalid_isinstance_type(second_arg):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,328
add_message
ref
function
self.add_message("isinstance-second-argument-not-valid-type", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,331
check_messages
ref
function
@check_messages(*(list(MSGS.keys())))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,332
visit_call
def
function
def visit_call(self, node: nodes.Call) -> None: """Check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function's definition """ called = safe_infer(node.func) self._check_not_callable(node, called) try: called, implicit_args, callable_name = _determine_callable(called) except ValueError: # Any error occurred during determining the function type, most of # those errors are handled by different warnings. return if called.args.args is None: if called.name == "isinstance": # Verify whether second argument of isinstance is a valid type self._check_isinstance_args(node) # Built-in functions have no argument information. return if len(called.argnames()) != len(set(called.argnames())): # Duplicate parameter name (see duplicate-argument). We can't really # make sense of the function call in this case, so just return. return # Build the set of keyword arguments, checking for duplicate keywords, # and count the positional arguments. call_site = astroid.arguments.CallSite.from_call(node) # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}` for keyword in call_site.duplicated_keywords: self.add_message("repeated-keyword", node=node, args=(keyword,)) if call_site.has_invalid_arguments() or call_site.has_invalid_keywords(): # Can't make sense of this. return # Has the function signature changed in ways we cannot reliably detect? if hasattr(called, "decorators") and decorated_with( called, self.config.signature_mutators ): return num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) overload_function = is_overload_stub(called) # Determine if we don't have a context for our call and we use variadics. node_scope = node.scope() if isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef)): has_no_context_positional_variadic = _no_context_variadic_positional( node, node_scope ) has_no_context_keywords_variadic = _no_context_variadic_keywords( node, node_scope ) else: has_no_context_positional_variadic = ( has_no_context_keywords_variadic ) = _False # These are coming from the functools.partial implementation in astroid already_filled_positionals = getattr(called, "filled_positionals", 0) already_filled_keywords = getattr(called, "filled_keywords", {}) keyword_args += list(already_filled_keywords) num_positional_args += implicit_args + already_filled_positionals # Analyze the list of formal parameters. args = list(itertools.chain(called.args.posonlyargs or (), called.args.args)) num_mandatory_parameters = len(args) - len(called.args.defaults) parameters: List[List[Any]] = [] parameter_name_to_index = {} for i, arg in enumerate(args): if isinstance(arg, nodes.Tuple): name = None # Don't store any parameter names within the tuple, since those # are not assignable from keyword arguments. else: assert isinstance(arg, nodes.AssignName) # This occurs with: # def f( (a), (b) ): pass name = arg.name parameter_name_to_index[name] = i if i >= num_mandatory_parameters: defval = called.args.defaults[i - num_mandatory_parameters] else: defval = None parameters.append([(name, defval), _False]) kwparams = {} for i, arg in enumerate(called.args.kwonlyargs): if isinstance(arg, nodes.Keyword): name = arg.arg else: assert isinstance(arg, nodes.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], _False] self._check_argument_order( node, call_site, called, [p[0][0] for p in parameters] ) # 1. Match the positional arguments. for i in range(num_positional_args): if i < len(parameters): parameters[i][1] = _True elif called.args.vararg is not None: # The remaining positional arguments get assigned to the *args # parameter. break elif not overload_function: # Too many positional arguments. self.add_message( "too-many-function-args", node=node, args=(callable_name,) ) break # 2. Match the keyword arguments. for keyword in keyword_args: if keyword in parameter_name_to_index: i = parameter_name_to_index[keyword] if parameters[i][1]: # Duplicate definition of function parameter. # Might be too hardcoded, but this can actually # happen when using str.format and `self` is passed # by keyword argument, as in `.format(self=self)`. # It's perfectly valid to so, so we're just skipping # it if that's the case. if not (keyword == "self" and called.qname() in STR_FORMAT): self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: parameters[i][1] = _True elif keyword in kwparams: if kwparams[keyword][1]: # Duplicate definition of function parameter. self.add_message( "redundant-keyword-arg", node=node, args=(keyword, callable_name), ) else: kwparams[keyword][1] = _True elif called.args.kwarg is not None: # The keyword argument gets assigned to the **kwargs parameter. pass elif isinstance( called, nodes.FunctionDef ) and self._keyword_argument_is_in_all_decorator_returns(called, keyword): pass elif not overload_function: # Unexpected keyword argument. self.add_message( "unexpected-keyword-arg", node=node, args=(keyword, callable_name) ) # 3. Match the **kwargs, if any. if node.kwargs: for i, [(name, defval), assigned] in enumerate(parameters): # Assume that *kwargs provides values for all remaining # unassigned named parameters. if name is not None: parameters[i][1] = _True else: # **kwargs can't assign to tuples. pass # Check that any parameters without a default have been assigned # values. for [(name, defval), assigned] in parameters: if (defval is None) and not assigned: display_name = "<tuple>" if name is None else repr(name) if not has_no_context_positional_variadic and not overload_function: self.add_message( "no-value-for-parameter", node=node, args=(display_name, callable_name), ) for name, val in kwparams.items(): defval, assigned = val if ( defval is None and not assigned and not has_no_context_keywords_variadic and not overload_function ): self.add_message("missing-kwoa", node=node, args=(name, callable_name)) @staticmethod def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,337
safe_infer
ref
function
called = safe_infer(node.func)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,339
_check_not_callable
ref
function
self._check_not_callable(node, called)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,342
_determine_callable
ref
function
called, implicit_args, callable_name = _determine_callable(called)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,351
_check_isinstance_args
ref
function
self._check_isinstance_args(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,355
argnames
ref
function
if len(called.argnames()) != len(set(called.argnames())):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,355
argnames
ref
function
if len(called.argnames()) != len(set(called.argnames())):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,362
from_call
ref
function
call_site = astroid.arguments.CallSite.from_call(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,366
add_message
ref
function
self.add_message("repeated-keyword", node=node, args=(keyword,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,368
has_invalid_arguments
ref
function
if call_site.has_invalid_arguments() or call_site.has_invalid_keywords():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,368
has_invalid_keywords
ref
function
if call_site.has_invalid_arguments() or call_site.has_invalid_keywords():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,373
decorated_with
ref
function
if hasattr(called, "decorators") and decorated_with(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,380
is_overload_stub
ref
function
overload_function = is_overload_stub(called)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,383
scope
ref
function
node_scope = node.scope()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,385
_no_context_variadic_positional
ref
function
has_no_context_positional_variadic = _no_context_variadic_positional(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,388
_no_context_variadic_keywords
ref
function
has_no_context_keywords_variadic = _no_context_variadic_keywords(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,434
_check_argument_order
ref
function
self._check_argument_order(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,448
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,465
qname
ref
function
if not (keyword == "self" and called.qname() in STR_FORMAT):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,466
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,476
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,488
_keyword_argument_is_in_all_decorator_returns
ref
function
) and self._keyword_argument_is_in_all_decorator_returns(called, keyword):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,492
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,513
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,527
add_message
ref
function
self.add_message("missing-kwoa", node=node, args=(name, callable_name))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,530
_keyword_argument_is_in_all_decorator_returns
def
function
def _keyword_argument_is_in_all_decorator_returns( func: nodes.FunctionDef, keyword: str ) -> bool: """Check if the keyword argument exists in all signatures of the return values of all decorators of the function. """ if not func.decorators: return _False for decorator in func.decorators.nodes: inferred = safe_infer(decorator) # If we can't infer the decorator we assume it satisfies consumes # the keyword, so we don't raise false positives if not inferred: return _True # We only check arguments of function decorators if not isinstance(inferred, nodes.FunctionDef): return _False for return_value in inferred.infer_call_result(): # infer_call_result() returns nodes.Const.None for None return values # so this also catches non-returning decorators if not isinstance(return_value, nodes.FunctionDef): return _False # If the return value uses a kwarg the keyword will be consumed if return_value.args.kwarg: continue # Check if the keyword is another type of argument if return_value.args.is_argument(keyword): continue return _False return _True def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,540
safe_infer
ref
function
inferred = safe_infer(decorator)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,551
infer_call_result
ref
function
for return_value in inferred.infer_call_result():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,562
is_argument
ref
function
if return_value.args.is_argument(keyword):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,569
_check_invalid_sequence_index
def
function
def _check_invalid_sequence_index(self, subscript: nodes.Subscript): # Look for index operations where the parent is a sequence type. # If the types can be determined, only allow indices to be int, # slice or instances with __index__. parent_type = safe_infer(subscript.value) if not isinstance( parent_type, (nodes.ClassDef, astroid.Instance) ) or not has_known_bases(parent_type): return None # Determine what method on the parent this index will use # The parent of this node will be a Subscript, and the parent of that # node determines if the Subscript is a get, set, or delete operation. if subscript.ctx is astroid.Store: methodname = "__setitem__" elif subscript.ctx is astroid.Del: methodname = "__delitem__" else: methodname = "__getitem__" # Check if this instance's __getitem__, __setitem__, or __delitem__, as # appropriate to the statement, is implemented in a builtin sequence # type. This way we catch subclasses of sequence types but skip classes # that override __getitem__ and which may allow non-integer indices. try: methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname) if methods is astroid.Uninferable: return None itemmethod = methods[0] except ( astroid.AttributeInferenceError, IndexError, ): return None if ( not isinstance(itemmethod, nodes.FunctionDef) or itemmethod.root().name != "builtins" or not itemmethod.parent or itemmethod.parent.frame().name not in SEQUENCE_TYPES ): return None # For ExtSlice objects coming from visit_extslice, no further # inference is necessary, since if we got this far the ExtSlice # is an error. if isinstance(subscript.value, nodes.ExtSlice): index_type = subscript.value else: index_type = safe_infer(subscript.slice) if index_type is None or index_type is astroid.Uninferable: return None # Constants must be of type int if isinstance(index_type, nodes.Const): if isinstance(index_type.value, int): return None # Instance values must be int, slice, or have an __index__ method elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.slice"}: return None try: index_type.getattr("__index__") return None except astroid.NotFoundError: pass elif isinstance(index_type, nodes.Slice): # A slice can be present # here after inferring the index node, which could # be a `slice(...)` call for instance. return self._check_invalid_slice_index(index_type) # Anything else is an error self.add_message("invalid-sequence-index", node=subscript) return None def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,573
safe_infer
ref
function
parent_type = safe_infer(subscript.value)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,576
has_known_bases
ref
function
) or not has_known_bases(parent_type):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,594
lookup
ref
function
methods = astroid.interpreter.dunder_lookup.lookup(parent_type, methodname)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,605
root
ref
function
or itemmethod.root().name != "builtins"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,607
frame
ref
function
or itemmethod.parent.frame().name not in SEQUENCE_TYPES
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,617
safe_infer
ref
function
index_type = safe_infer(subscript.slice)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,626
pytype
ref
function
if index_type.pytype() in {"builtins.int", "builtins.slice"}:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,637
_check_invalid_slice_index
ref
function
return self._check_invalid_slice_index(index_type)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,640
add_message
ref
function
self.add_message("invalid-sequence-index", node=subscript)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,643
_check_not_callable
def
function
def _check_not_callable( self, node: nodes.Call, inferred_call: Optional[nodes.NodeNG] ) -> None: """Checks to see if the not-callable message should be emitted. Only functions, generators and objects defining __call__ are "callable" We ignore instances of descriptors since astroid cannot properly handle them yet """ # Handle uninferable calls if not inferred_call or inferred_call.callable(): self._check_uninferable_call(node) return if not isinstance(inferred_call, astroid.Instance): self.add_message("not-callable", node=node, args=node.func.as_string()) return # Don't emit if we can't make sure this object is callable. if not has_known_bases(inferred_call): return if inferred_call.parent and isinstance(inferred_call.scope(), nodes.ClassDef): # Ignore descriptor instances if "__get__" in inferred_call.locals: return # NamedTuple instances are callable if inferred_call.qname() == "typing.NamedTuple": return self.add_message("not-callable", node=node, args=node.func.as_string()) @check_messages("invalid-sequence-index") def visit_extslice(self, node: nodes.ExtSlice) -> None: if not node.parent or not hasattr(node.parent, "value"): return None # Check extended slice objects as if they were used as a sequence # index to check if the object being sliced can support them return self._check_invalid_sequence_index(node.parent) def _check_invalid_slice_index(self, node: nodes.Slice) -> None: # Check the type of each part of the slice invalid_slices_nodes: List[nodes.NodeNG] = [] for index in (node.lower, node.upper, node.step): if index is None: continue index_type = safe_infer(index) if index_type is None or index_type is astroid.Uninferable: continue # Constants must be of type int or None if isinstance(index_type, nodes.Const): if isinstance(index_type.value, (int, type(None))): continue # Instance values must be of type int, None or an object # with __index__ elif isinstance(index_type, astroid.Instance): if index_type.pytype() in {"builtins.int", "builtins.NoneType"}: continue try: index_type.getattr("__index__") return except astroid.NotFoundError: pass invalid_slices_nodes.append(index) if not invalid_slices_nodes: return # Anything else is an error, unless the object that is indexed # is a custom object, which knows how to handle this kind of slices parent = node.parent if isinstance(parent, nodes.ExtSlice): parent = parent.parent if isinstance(parent, nodes.Subscript): inferred = safe_infer(parent.value) if inferred is None or inferred is astroid.Uninferable: # Don't know what this is return known_objects = ( nodes.List, nodes.Dict, nodes.Tuple, astroid.objects.FrozenSet, nodes.Set, ) if not isinstance(inferred, known_objects): # Might be an instance that knows how to handle this slice object return for snode in invalid_slices_nodes: self.add_message("invalid-slice-index", node=snode) @check_messages("not-context-manager") def visit_with(self, node: nodes.With) -> None: for ctx_mgr, _ in node.items: context = astroid.context.InferenceContext() inferred = safe_infer(ctx_mgr, context=context) if inferred is None or inferred is astroid.Uninferable: continue if isinstance(inferred, astroid.bases.Generator): # Check if we are dealing with a function decorated # with contextlib.contextmanager. if decorated_with( inferred.parent, self.config.contextmanager_decorators ): continue # If the parent of the generator is not the context manager itself, # that means that it could have been returned from another # function which was the real context manager. # The following approach is more of a hack rather than a real # solution: walk all the inferred statements for the # given *ctx_mgr* and if you find one function scope # which is decorated, consider it to be the real # manager and give up, otherwise emit not-context-manager. # See the test file for not_context_manager for a couple # of self explaining tests. # Retrieve node from all previously visited nodes in the # inference history context_path_names: Iterator[Any] = filter( None, _unflatten(context.path) ) inferred_paths = _flatten_container( safe_infer(path) for path in context_path_names ) for inferred_path in inferred_paths: if not inferred_path: continue scope = inferred_path.scope() if not isinstance(scope, nodes.FunctionDef): continue if decorated_with(scope, self.config.contextmanager_decorators): break else: self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) else: try: inferred.getattr("__enter__") inferred.getattr("__exit__") except astroid.NotFoundError: if isinstance(inferred, astroid.Instance): # If we do not know the bases of this class, # just skip it. if not has_known_bases(inferred): continue # Just ignore mixin classes. if self.config.ignore_mixin_members: if inferred.name[-5:].lower() == "mixin": continue self.add_message( "not-context-manager", node=node, args=(inferred.name,) ) @check_messages("invalid-unary-operand-type") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """Detect TypeErrors for unary operands.""" for error in node.type_errors(): # Let the error customize its output. self.add_message("invalid-unary-operand-type", args=str(error), node=node) @check_messages("unsupported-binary-operation") def visit_binop(self, node: nodes.BinOp) -> None: if node.op == "|": self._detect_unsupported_alternative_union_syntax(node) def _detect_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Detect if unsupported alternative Union syntax (PEP 604) was used.""" if self._py310_plus: # 310+ supports the new syntax return if isinstance( node.parent, TYPE_ANNOTATION_NODES_TYPES ) and not is_postponed_evaluation_enabled(node): # Use in type annotations only allowed if # postponed evaluation is enabled. self._check_unsupported_alternative_union_syntax(node) if isinstance( node.parent, ( nodes.Assign, nodes.Call, nodes.Keyword, nodes.Dict, nodes.Tuple, nodes.Set, nodes.List, nodes.BinOp, ), ): # Check other contexts the syntax might appear, but are invalid. # Make sure to filter context if postponed evaluation is enabled # and parent is allowed node type. allowed_nested_syntax = _False if is_postponed_evaluation_enabled(node): parent_node = node.parent while _True: if isinstance(parent_node, TYPE_ANNOTATION_NODES_TYPES): allowed_nested_syntax = _True break parent_node = parent_node.parent if isinstance(parent_node, nodes.Module): break if not allowed_nested_syntax: self._check_unsupported_alternative_union_syntax(node) def _check_unsupported_alternative_union_syntax(self, node: nodes.BinOp) -> None: """Check if left or right node is of type `type`.""" msg = "unsupported operand type(s) for |" for n in (node.left, node.right): n = astroid.helpers.object_type(n) if isinstance(n, nodes.ClassDef) and is_classdef_type(n): self.add_message("unsupported-binary-operation", args=msg, node=node) break @check_messages("unsupported-binary-operation") def _visit_binop(self, node: nodes.BinOp) -> None: """Detect TypeErrors for binary arithmetic operands.""" self._check_binop_errors(node) @check_messages("unsupported-binary-operation") def _visit_augassign(self, node: nodes.AugAssign) -> None: """Detect TypeErrors for augmented binary arithmetic operands.""" self._check_binop_errors(node) def _check_binop_errors(self, node): for error in node.type_errors(): # Let the error customize its output. if any( isinstance(obj, nodes.ClassDef) and not has_known_bases(obj) for obj in (error.left_type, error.right_type) ): continue self.add_message("unsupported-binary-operation", args=str(error), node=node) def _check_membership_test(self, node): if is_inside_abstract_class(node): return if is_comprehension(node): return inferred = safe_infer(node) if inferred is None or inferred is astroid.Uninferable: return if not supports_membership_test(inferred): self.add_message( "unsupported-membership-test", args=node.as_string(), node=node ) @check_messages("unsupported-membership-test") def visit_compare(self, node: nodes.Compare) -> None: if len(node.ops) != 1: return op, right = node.ops[0] if op in {"in", "not in"}: self._check_membership_test(right) @check_messages( "unsubscriptable-object", "unsupported-assignment-operation", "unsupported-delete-operation", "unhashable-dict-key", "invalid-sequence-index", "invalid-slice-index", ) def visit_subscript(self, node: nodes.Subscript) -> None: self._check_invalid_sequence_index(node) supported_protocol: Optional[Callable[[Any, Any], bool]] = None if isinstance(node.value, (nodes.ListComp, nodes.DictComp)): return if isinstance(node.value, nodes.Dict): # Assert dict key is hashable inferred = safe_infer(node.slice) if inferred and inferred != astroid.Uninferable: try: hash_fn = next(inferred.igetattr("__hash__")) except astroid.InferenceError: pass else: if getattr(hash_fn, "value", _True) is None: self.add_message("unhashable-dict-key", node=node.value) if node.ctx == astroid.Load: supported_protocol = supports_getitem msg = "unsubscriptable-object" elif node.ctx == astroid.Store: supported_protocol = supports_setitem msg = "unsupported-assignment-operation" elif node.ctx == astroid.Del: supported_protocol = supports_delitem msg = "unsupported-delete-operation" if isinstance(node.value, nodes.SetComp): self.add_message(msg, args=node.value.as_string(), node=node.value) return if is_inside_abstract_class(node): return inferred = safe_infer(node.value) if inferred is None or inferred is astroid.Uninferable: return if getattr(inferred, "decorators", None): first_decorator = astroid.helpers.safe_infer(inferred.decorators.nodes[0]) if isinstance(first_decorator, nodes.ClassDef): inferred = first_decorator.instantiate_class() else: return # It would be better to handle function # decorators, but let's start slow. if supported_protocol and not supported_protocol(inferred, node): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") def visit_for(self, node: nodes.For) -> None: if not isinstance(node.target, nodes.Tuple): # target is not a tuple return if not len(node.target.elts) == 2: # target is not a tuple of two elements return iterable = node.iter if not isinstance(iterable, nodes.Name): # it's not a bare variable return inferred = safe_infer(iterable) if not inferred: return if not isinstance(inferred, nodes.Dict): # the iterable is not a dict return if all(isinstance(i[0], nodes.Tuple) for i in inferred.items): # if all keys are tuples return self.add_message("dict-iter-missing-items", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,653
_check_uninferable_call
ref
function
self._check_uninferable_call(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,657
add_message
ref
function
self.add_message("not-callable", node=node, args=node.func.as_string())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,657
as_string
ref
function
self.add_message("not-callable", node=node, args=node.func.as_string())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/typecheck.py
pylint/checkers/typecheck.py
1,661
has_known_bases
ref
function
if not has_known_bases(inferred_call):