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/classes/class_checker.py
pylint/checkers/classes/class_checker.py
932
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
935
is_attr_private
ref
function
if not is_attr_private(assign_name.name):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
937
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
951
add_message
ref
function
self.add_message("unused-private-member", node=assign_name, args=args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
953
_check_unused_private_attributes
def
function
def _check_unused_private_attributes(self, node: nodes.ClassDef) -> None: for assign_attr in node.nodes_of_class(nodes.AssignAttr): if not is_attr_private(assign_attr.attrname) or not isinstance( assign_attr.expr, nodes.Name ): continue # Logic for checking false positive when using __new__, # Get the returned object names of the __new__ magic function # Then check if the attribute was consumed in other instance methods acceptable_obj_names: List[str] = ["self"] scope = assign_attr.scope() if isinstance(scope, nodes.FunctionDef) and scope.name == "__new__": acceptable_obj_names.extend( [ return_node.value.name for return_node in scope.nodes_of_class(nodes.Return) if isinstance(return_node.value, nodes.Name) ] ) for attribute in node.nodes_of_class(nodes.Attribute): if attribute.attrname != assign_attr.attrname: continue if self._is_type_self_call(attribute.expr): continue if assign_attr.expr.name in { "cls", node.name, } and attribute.expr.name in {"cls", "self", node.name}: # If assigned to cls or class name, can be accessed by cls/self/class name break if ( assign_attr.expr.name in acceptable_obj_names and attribute.expr.name == "self" ): # If assigned to self.attrib, can only be accessed by self # Or if __new__ was used, the returned object names are acceptable break if assign_attr.expr.name == attribute.expr.name == node.name: # Recognise attributes which are accessed via the class name break else: args = (node.name, assign_attr.attrname) self.add_message("unused-private-member", node=assign_attr, args=args) def _check_attribute_defined_outside_init(self, cnode: nodes.ClassDef) -> None: # check access to existent members on non metaclass classes if self._ignore_mixin and self._mixin_class_rgx.match(cnode.name): # We are in a mixin class. No need to try to figure out if # something is missing, since it is most likely that it will # miss. return accessed = self._accessed.accessed(cnode) if cnode.type != "metaclass": self._check_accessed_members(cnode, accessed) # checks attributes are defined in an allowed method such as __init__ if not self.linter.is_message_enabled("attribute-defined-outside-init"): return defining_methods = self.config.defining_attr_methods current_module = cnode.root() for attr, nodes_lst in cnode.instance_attrs.items(): # Exclude `__dict__` as it is already defined. if attr == "__dict__": continue # Skip nodes which are not in the current module and it may screw up # the output, while it's not worth it nodes_lst = [ n for n in nodes_lst if not isinstance( n.statement(future=_True), (nodes.Delete, nodes.AugAssign) ) and n.root() is current_module ] if not nodes_lst: continue # error detected by typechecking # Check if any method attr is defined in is a defining method # or if we have the attribute defined in a setter. frames = (node.frame(future=_True) for node in nodes_lst) if any( frame.name in defining_methods or is_property_setter(frame) for frame in frames ): continue # check attribute is defined in a parent's __init__ for parent in cnode.instance_attr_ancestors(attr): attr_defined = _False # check if any parent method attr is defined in is a defining method for node in parent.instance_attrs[attr]: if node.frame(future=_True).name in defining_methods: attr_defined = _True if attr_defined: # we're done :) break else: # check attribute is defined as a class attribute try: cnode.local_attr(attr) except astroid.NotFoundError: for node in nodes_lst: if node.frame(future=_True).name not in defining_methods: # If the attribute was set by a call in any # of the defining methods, then don't emit # the warning. if _called_in_methods( node.frame(future=_True), cnode, defining_methods ): continue self.add_message( "attribute-defined-outside-init", args=attr, node=node ) def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check method arguments, overriding.""" # ignore actual functions if not node.is_method(): return self._check_useless_super_delegation(node) self._check_property_with_parameters(node) # 'is_method()' is called and makes sure that this is a 'nodes.ClassDef' klass = node.parent.frame(future=_True) # type: nodes.ClassDef self._meth_could_be_func = _True # check first argument is self if this is actually a method self._check_first_arg_for_type(node, klass.type == "metaclass") if node.name == "__init__": self._check_init(node, klass) return # check signature if the method overloads inherited method for overridden in klass.local_attr_ancestors(node.name): # get astroid for the searched method try: parent_function = overridden[node.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if not isinstance(parent_function, nodes.FunctionDef): continue self._check_signature(node, parent_function, "overridden", klass) self._check_invalid_overridden_method(node, parent_function) break if node.decorators: for decorator in node.decorators.nodes: if isinstance(decorator, nodes.Attribute) and decorator.attrname in { "getter", "setter", "deleter", }: # attribute affectation will call this method, not hiding it return if isinstance(decorator, nodes.Name): if decorator.name == "property": # attribute affectation will either call a setter or raise # an attribute error, anyway not hiding the function return # Infer the decorator and see if it returns something useful inferred = safe_infer(decorator) if not inferred: return if isinstance(inferred, nodes.FunctionDef): # Okay, it's a decorator, let's see what it can infer. try: inferred = next(inferred.infer_call_result(inferred)) except astroid.InferenceError: return try: if ( isinstance(inferred, (astroid.Instance, nodes.ClassDef)) and inferred.getattr("__get__") and inferred.getattr("__set__") ): return except astroid.AttributeInferenceError: pass # check if the method is hidden by an attribute try: overridden = klass.instance_attr(node.name)[0] overridden_frame = overridden.frame(future=_True) if ( isinstance(overridden_frame, nodes.FunctionDef) and overridden_frame.type == "method" ): overridden_frame = overridden_frame.parent.frame(future=_True) if not ( isinstance(overridden_frame, nodes.ClassDef) and klass.is_subtype_of(overridden_frame.qname()) ): return # If a subclass defined the method then it's not our fault. for ancestor in klass.ancestors(): if node.name in ancestor.instance_attrs and is_attr_private(node.name): return for obj in ancestor.lookup(node.name)[1]: if isinstance(obj, nodes.FunctionDef): return args = (overridden.root().name, overridden.fromlineno) self.add_message("method-hidden", args=args, node=node) except astroid.NotFoundError: pass visit_asyncfunctiondef = visit_functiondef def _check_useless_super_delegation(self, function): """Check if the given function node is an useless method override. We consider it *useless* if it uses the super() builtin, but having nothing additional whatsoever than not implementing the method at all. If the method uses super() to delegate an operation to the rest of the MRO, and if the method called is the same as the current one, the arguments passed to super() are the same as the parameters that were passed to this method, then the method could be removed altogether, by letting other implementation to take precedence. """ if ( not function.is_method() # With decorators is a change of use or function.decorators ): return body = function.body if len(body) != 1: # Multiple statements, which means this overridden method # could do multiple things we are not aware of. return statement = body[0] if not isinstance(statement, (nodes.Expr, nodes.Return)): # Doing something else than what we are interested into. return call = statement.value if ( not isinstance(call, nodes.Call) # Not a super() attribute access. or not isinstance(call.func, nodes.Attribute) ): return # Should be a super call. try: super_call = next(call.func.expr.infer()) except astroid.InferenceError: return else: if not isinstance(super_call, astroid.objects.Super): return # The name should be the same. if call.func.attrname != function.name: return # Should be a super call with the MRO pointer being the # current class and the type being the current instance. current_scope = function.parent.scope() if ( super_call.mro_pointer != current_scope or not isinstance(super_call.type, astroid.Instance) or super_call.type.name != current_scope.name ): return # Check values of default args klass = function.parent.frame(future=_True) meth_node = None for overridden in klass.local_attr_ancestors(function.name): # get astroid for the searched method try: meth_node = overridden[function.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if ( not isinstance(meth_node, nodes.FunctionDef) # If the method have an ancestor which is not a # function then it is legitimate to redefine it or _has_different_parameters_default_value( meth_node.args, function.args ) ): return break # Detect if the parameters are the same as the call's arguments. params = _signature_from_arguments(function.args) args = _signature_from_call(call) if meth_node is not None: def form_annotations(arguments): annotations = chain( (arguments.posonlyargs_annotations or []), arguments.annotations ) return [ann.as_string() for ann in annotations if ann is not None] called_annotations = form_annotations(function.args) overridden_annotations = form_annotations(meth_node.args) if called_annotations and overridden_annotations: if called_annotations != overridden_annotations: return if _definition_equivalent_to_call(params, args): self.add_message( "useless-super-delegation", node=function, args=(function.name,) ) def _check_property_with_parameters(self, node): if ( node.args.args and len(node.args.args) > 1 and decorated_with_property(node) and not is_property_setter(node) ): self.add_message("property-with-parameters", node=node) def _check_invalid_overridden_method(self, function_node, parent_function_node): parent_is_property = decorated_with_property( parent_function_node ) or is_property_setter_or_deleter(parent_function_node) current_is_property = decorated_with_property( function_node ) or is_property_setter_or_deleter(function_node) if parent_is_property and not current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "property", function_node.type), node=function_node, ) elif not parent_is_property and current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "method", "property"), node=function_node, ) parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef) current_is_async = isinstance(function_node, nodes.AsyncFunctionDef) if parent_is_async and not current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "async", "non-async"), node=function_node, ) elif not parent_is_async and current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "non-async", "async"), node=function_node, ) if ( decorated_with(parent_function_node, ["typing.final"]) or uninferable_final_decorators(parent_function_node.decorators) ) and self._py38_plus: self.add_message( "overridden-final-method", args=(function_node.name, parent_function_node.parent.frame().name), node=function_node, ) def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
954
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
955
is_attr_private
ref
function
if not is_attr_private(assign_attr.attrname) or not isinstance(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
964
scope
ref
function
scope = assign_attr.scope()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
969
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
974
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
978
_is_type_self_call
ref
function
if self._is_type_self_call(attribute.expr):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,002
add_message
ref
function
self.add_message("unused-private-member", node=assign_attr, args=args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,004
_check_attribute_defined_outside_init
def
function
def _check_attribute_defined_outside_init(self, cnode: nodes.ClassDef) -> None: # check access to existent members on non metaclass classes if self._ignore_mixin and self._mixin_class_rgx.match(cnode.name): # We are in a mixin class. No need to try to figure out if # something is missing, since it is most likely that it will # miss. return accessed = self._accessed.accessed(cnode) if cnode.type != "metaclass": self._check_accessed_members(cnode, accessed) # checks attributes are defined in an allowed method such as __init__ if not self.linter.is_message_enabled("attribute-defined-outside-init"): return defining_methods = self.config.defining_attr_methods current_module = cnode.root() for attr, nodes_lst in cnode.instance_attrs.items(): # Exclude `__dict__` as it is already defined. if attr == "__dict__": continue # Skip nodes which are not in the current module and it may screw up # the output, while it's not worth it nodes_lst = [ n for n in nodes_lst if not isinstance( n.statement(future=_True), (nodes.Delete, nodes.AugAssign) ) and n.root() is current_module ] if not nodes_lst: continue # error detected by typechecking # Check if any method attr is defined in is a defining method # or if we have the attribute defined in a setter. frames = (node.frame(future=_True) for node in nodes_lst) if any( frame.name in defining_methods or is_property_setter(frame) for frame in frames ): continue # check attribute is defined in a parent's __init__ for parent in cnode.instance_attr_ancestors(attr): attr_defined = _False # check if any parent method attr is defined in is a defining method for node in parent.instance_attrs[attr]: if node.frame(future=_True).name in defining_methods: attr_defined = _True if attr_defined: # we're done :) break else: # check attribute is defined as a class attribute try: cnode.local_attr(attr) except astroid.NotFoundError: for node in nodes_lst: if node.frame(future=_True).name not in defining_methods: # If the attribute was set by a call in any # of the defining methods, then don't emit # the warning. if _called_in_methods( node.frame(future=_True), cnode, defining_methods ): continue self.add_message( "attribute-defined-outside-init", args=attr, node=node ) def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check method arguments, overriding.""" # ignore actual functions if not node.is_method(): return self._check_useless_super_delegation(node) self._check_property_with_parameters(node) # 'is_method()' is called and makes sure that this is a 'nodes.ClassDef' klass = node.parent.frame(future=_True) # type: nodes.ClassDef self._meth_could_be_func = _True # check first argument is self if this is actually a method self._check_first_arg_for_type(node, klass.type == "metaclass") if node.name == "__init__": self._check_init(node, klass) return # check signature if the method overloads inherited method for overridden in klass.local_attr_ancestors(node.name): # get astroid for the searched method try: parent_function = overridden[node.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if not isinstance(parent_function, nodes.FunctionDef): continue self._check_signature(node, parent_function, "overridden", klass) self._check_invalid_overridden_method(node, parent_function) break if node.decorators: for decorator in node.decorators.nodes: if isinstance(decorator, nodes.Attribute) and decorator.attrname in { "getter", "setter", "deleter", }: # attribute affectation will call this method, not hiding it return if isinstance(decorator, nodes.Name): if decorator.name == "property": # attribute affectation will either call a setter or raise # an attribute error, anyway not hiding the function return # Infer the decorator and see if it returns something useful inferred = safe_infer(decorator) if not inferred: return if isinstance(inferred, nodes.FunctionDef): # Okay, it's a decorator, let's see what it can infer. try: inferred = next(inferred.infer_call_result(inferred)) except astroid.InferenceError: return try: if ( isinstance(inferred, (astroid.Instance, nodes.ClassDef)) and inferred.getattr("__get__") and inferred.getattr("__set__") ): return except astroid.AttributeInferenceError: pass # check if the method is hidden by an attribute try: overridden = klass.instance_attr(node.name)[0] overridden_frame = overridden.frame(future=_True) if ( isinstance(overridden_frame, nodes.FunctionDef) and overridden_frame.type == "method" ): overridden_frame = overridden_frame.parent.frame(future=_True) if not ( isinstance(overridden_frame, nodes.ClassDef) and klass.is_subtype_of(overridden_frame.qname()) ): return # If a subclass defined the method then it's not our fault. for ancestor in klass.ancestors(): if node.name in ancestor.instance_attrs and is_attr_private(node.name): return for obj in ancestor.lookup(node.name)[1]: if isinstance(obj, nodes.FunctionDef): return args = (overridden.root().name, overridden.fromlineno) self.add_message("method-hidden", args=args, node=node) except astroid.NotFoundError: pass visit_asyncfunctiondef = visit_functiondef def _check_useless_super_delegation(self, function): """Check if the given function node is an useless method override. We consider it *useless* if it uses the super() builtin, but having nothing additional whatsoever than not implementing the method at all. If the method uses super() to delegate an operation to the rest of the MRO, and if the method called is the same as the current one, the arguments passed to super() are the same as the parameters that were passed to this method, then the method could be removed altogether, by letting other implementation to take precedence. """ if ( not function.is_method() # With decorators is a change of use or function.decorators ): return body = function.body if len(body) != 1: # Multiple statements, which means this overridden method # could do multiple things we are not aware of. return statement = body[0] if not isinstance(statement, (nodes.Expr, nodes.Return)): # Doing something else than what we are interested into. return call = statement.value if ( not isinstance(call, nodes.Call) # Not a super() attribute access. or not isinstance(call.func, nodes.Attribute) ): return # Should be a super call. try: super_call = next(call.func.expr.infer()) except astroid.InferenceError: return else: if not isinstance(super_call, astroid.objects.Super): return # The name should be the same. if call.func.attrname != function.name: return # Should be a super call with the MRO pointer being the # current class and the type being the current instance. current_scope = function.parent.scope() if ( super_call.mro_pointer != current_scope or not isinstance(super_call.type, astroid.Instance) or super_call.type.name != current_scope.name ): return # Check values of default args klass = function.parent.frame(future=_True) meth_node = None for overridden in klass.local_attr_ancestors(function.name): # get astroid for the searched method try: meth_node = overridden[function.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if ( not isinstance(meth_node, nodes.FunctionDef) # If the method have an ancestor which is not a # function then it is legitimate to redefine it or _has_different_parameters_default_value( meth_node.args, function.args ) ): return break # Detect if the parameters are the same as the call's arguments. params = _signature_from_arguments(function.args) args = _signature_from_call(call) if meth_node is not None: def form_annotations(arguments): annotations = chain( (arguments.posonlyargs_annotations or []), arguments.annotations ) return [ann.as_string() for ann in annotations if ann is not None] called_annotations = form_annotations(function.args) overridden_annotations = form_annotations(meth_node.args) if called_annotations and overridden_annotations: if called_annotations != overridden_annotations: return if _definition_equivalent_to_call(params, args): self.add_message( "useless-super-delegation", node=function, args=(function.name,) ) def _check_property_with_parameters(self, node): if ( node.args.args and len(node.args.args) > 1 and decorated_with_property(node) and not is_property_setter(node) ): self.add_message("property-with-parameters", node=node) def _check_invalid_overridden_method(self, function_node, parent_function_node): parent_is_property = decorated_with_property( parent_function_node ) or is_property_setter_or_deleter(parent_function_node) current_is_property = decorated_with_property( function_node ) or is_property_setter_or_deleter(function_node) if parent_is_property and not current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "property", function_node.type), node=function_node, ) elif not parent_is_property and current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "method", "property"), node=function_node, ) parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef) current_is_async = isinstance(function_node, nodes.AsyncFunctionDef) if parent_is_async and not current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "async", "non-async"), node=function_node, ) elif not parent_is_async and current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "non-async", "async"), node=function_node, ) if ( decorated_with(parent_function_node, ["typing.final"]) or uninferable_final_decorators(parent_function_node.decorators) ) and self._py38_plus: self.add_message( "overridden-final-method", args=(function_node.name, parent_function_node.parent.frame().name), node=function_node, ) def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,006
match
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,012
accessed
ref
function
accessed = self._accessed.accessed(cnode)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,014
_check_accessed_members
ref
function
self._check_accessed_members(cnode, accessed)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,016
is_message_enabled
ref
function
if not self.linter.is_message_enabled("attribute-defined-outside-init"):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,019
root
ref
function
current_module = cnode.root()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,031
statement
ref
function
n.statement(future=True), (nodes.Delete, nodes.AugAssign)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,033
root
ref
function
and n.root() is current_module
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,040
frame
ref
function
frames = (node.frame(future=True) for node in nodes_lst)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,042
is_property_setter
ref
function
frame.name in defining_methods or is_property_setter(frame)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,048
instance_attr_ancestors
ref
function
for parent in cnode.instance_attr_ancestors(attr):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,052
frame
ref
function
if node.frame(future=True).name in defining_methods:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,060
local_attr
ref
function
cnode.local_attr(attr)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,063
frame
ref
function
if node.frame(future=True).name not in defining_methods:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,067
_called_in_methods
ref
function
if _called_in_methods(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,068
frame
ref
function
node.frame(future=True), cnode, defining_methods
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,071
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,075
visit_functiondef
def
function
def visit_functiondef(self, node: nodes.FunctionDef) -> None: """Check method arguments, overriding.""" # ignore actual functions if not node.is_method(): return self._check_useless_super_delegation(node) self._check_property_with_parameters(node) # 'is_method()' is called and makes sure that this is a 'nodes.ClassDef' klass = node.parent.frame(future=_True) # type: nodes.ClassDef self._meth_could_be_func = _True # check first argument is self if this is actually a method self._check_first_arg_for_type(node, klass.type == "metaclass") if node.name == "__init__": self._check_init(node, klass) return # check signature if the method overloads inherited method for overridden in klass.local_attr_ancestors(node.name): # get astroid for the searched method try: parent_function = overridden[node.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if not isinstance(parent_function, nodes.FunctionDef): continue self._check_signature(node, parent_function, "overridden", klass) self._check_invalid_overridden_method(node, parent_function) break if node.decorators: for decorator in node.decorators.nodes: if isinstance(decorator, nodes.Attribute) and decorator.attrname in { "getter", "setter", "deleter", }: # attribute affectation will call this method, not hiding it return if isinstance(decorator, nodes.Name): if decorator.name == "property": # attribute affectation will either call a setter or raise # an attribute error, anyway not hiding the function return # Infer the decorator and see if it returns something useful inferred = safe_infer(decorator) if not inferred: return if isinstance(inferred, nodes.FunctionDef): # Okay, it's a decorator, let's see what it can infer. try: inferred = next(inferred.infer_call_result(inferred)) except astroid.InferenceError: return try: if ( isinstance(inferred, (astroid.Instance, nodes.ClassDef)) and inferred.getattr("__get__") and inferred.getattr("__set__") ): return except astroid.AttributeInferenceError: pass # check if the method is hidden by an attribute try: overridden = klass.instance_attr(node.name)[0] overridden_frame = overridden.frame(future=_True) if ( isinstance(overridden_frame, nodes.FunctionDef) and overridden_frame.type == "method" ): overridden_frame = overridden_frame.parent.frame(future=_True) if not ( isinstance(overridden_frame, nodes.ClassDef) and klass.is_subtype_of(overridden_frame.qname()) ): return # If a subclass defined the method then it's not our fault. for ancestor in klass.ancestors(): if node.name in ancestor.instance_attrs and is_attr_private(node.name): return for obj in ancestor.lookup(node.name)[1]: if isinstance(obj, nodes.FunctionDef): return args = (overridden.root().name, overridden.fromlineno) self.add_message("method-hidden", args=args, node=node) except astroid.NotFoundError: pass visit_asyncfunctiondef = visit_functiondef def _check_useless_super_delegation(self, function): """Check if the given function node is an useless method override. We consider it *useless* if it uses the super() builtin, but having nothing additional whatsoever than not implementing the method at all. If the method uses super() to delegate an operation to the rest of the MRO, and if the method called is the same as the current one, the arguments passed to super() are the same as the parameters that were passed to this method, then the method could be removed altogether, by letting other implementation to take precedence. """ if ( not function.is_method() # With decorators is a change of use or function.decorators ): return body = function.body if len(body) != 1: # Multiple statements, which means this overridden method # could do multiple things we are not aware of. return statement = body[0] if not isinstance(statement, (nodes.Expr, nodes.Return)): # Doing something else than what we are interested into. return call = statement.value if ( not isinstance(call, nodes.Call) # Not a super() attribute access. or not isinstance(call.func, nodes.Attribute) ): return # Should be a super call. try: super_call = next(call.func.expr.infer()) except astroid.InferenceError: return else: if not isinstance(super_call, astroid.objects.Super): return # The name should be the same. if call.func.attrname != function.name: return # Should be a super call with the MRO pointer being the # current class and the type being the current instance. current_scope = function.parent.scope() if ( super_call.mro_pointer != current_scope or not isinstance(super_call.type, astroid.Instance) or super_call.type.name != current_scope.name ): return # Check values of default args klass = function.parent.frame(future=_True) meth_node = None for overridden in klass.local_attr_ancestors(function.name): # get astroid for the searched method try: meth_node = overridden[function.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if ( not isinstance(meth_node, nodes.FunctionDef) # If the method have an ancestor which is not a # function then it is legitimate to redefine it or _has_different_parameters_default_value( meth_node.args, function.args ) ): return break # Detect if the parameters are the same as the call's arguments. params = _signature_from_arguments(function.args) args = _signature_from_call(call) if meth_node is not None: def form_annotations(arguments): annotations = chain( (arguments.posonlyargs_annotations or []), arguments.annotations ) return [ann.as_string() for ann in annotations if ann is not None] called_annotations = form_annotations(function.args) overridden_annotations = form_annotations(meth_node.args) if called_annotations and overridden_annotations: if called_annotations != overridden_annotations: return if _definition_equivalent_to_call(params, args): self.add_message( "useless-super-delegation", node=function, args=(function.name,) ) def _check_property_with_parameters(self, node): if ( node.args.args and len(node.args.args) > 1 and decorated_with_property(node) and not is_property_setter(node) ): self.add_message("property-with-parameters", node=node) def _check_invalid_overridden_method(self, function_node, parent_function_node): parent_is_property = decorated_with_property( parent_function_node ) or is_property_setter_or_deleter(parent_function_node) current_is_property = decorated_with_property( function_node ) or is_property_setter_or_deleter(function_node) if parent_is_property and not current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "property", function_node.type), node=function_node, ) elif not parent_is_property and current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "method", "property"), node=function_node, ) parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef) current_is_async = isinstance(function_node, nodes.AsyncFunctionDef) if parent_is_async and not current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "async", "non-async"), node=function_node, ) elif not parent_is_async and current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "non-async", "async"), node=function_node, ) if ( decorated_with(parent_function_node, ["typing.final"]) or uninferable_final_decorators(parent_function_node.decorators) ) and self._py38_plus: self.add_message( "overridden-final-method", args=(function_node.name, parent_function_node.parent.frame().name), node=function_node, ) def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,078
is_method
ref
function
if not node.is_method():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,081
_check_useless_super_delegation
ref
function
self._check_useless_super_delegation(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,082
_check_property_with_parameters
ref
function
self._check_property_with_parameters(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,085
frame
ref
function
klass = node.parent.frame(future=True) # type: nodes.ClassDef
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,088
_check_first_arg_for_type
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,090
_check_init
ref
function
self._check_init(node, klass)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,093
local_attr_ancestors
ref
function
for overridden in klass.local_attr_ancestors(node.name):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,104
_check_signature
ref
function
self._check_signature(node, parent_function, "overridden", klass)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,105
_check_invalid_overridden_method
ref
function
self._check_invalid_overridden_method(node, parent_function)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,124
safe_infer
ref
function
inferred = safe_infer(decorator)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,130
infer_call_result
ref
function
inferred = next(inferred.infer_call_result(inferred))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,145
instance_attr
ref
function
overridden = klass.instance_attr(node.name)[0]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,146
frame
ref
function
overridden_frame = overridden.frame(future=True)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,151
frame
ref
function
overridden_frame = overridden_frame.parent.frame(future=True)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,154
is_subtype_of
ref
function
and klass.is_subtype_of(overridden_frame.qname())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,154
qname
ref
function
and klass.is_subtype_of(overridden_frame.qname())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,159
ancestors
ref
function
for ancestor in klass.ancestors():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,160
is_attr_private
ref
function
if node.name in ancestor.instance_attrs and is_attr_private(node.name):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,162
lookup
ref
function
for obj in ancestor.lookup(node.name)[1]:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,165
root
ref
function
args = (overridden.root().name, overridden.fromlineno)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,166
add_message
ref
function
self.add_message("method-hidden", args=args, node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,172
_check_useless_super_delegation
def
function
def _check_useless_super_delegation(self, function): """Check if the given function node is an useless method override. We consider it *useless* if it uses the super() builtin, but having nothing additional whatsoever than not implementing the method at all. If the method uses super() to delegate an operation to the rest of the MRO, and if the method called is the same as the current one, the arguments passed to super() are the same as the parameters that were passed to this method, then the method could be removed altogether, by letting other implementation to take precedence. """ if ( not function.is_method() # With decorators is a change of use or function.decorators ): return body = function.body if len(body) != 1: # Multiple statements, which means this overridden method # could do multiple things we are not aware of. return statement = body[0] if not isinstance(statement, (nodes.Expr, nodes.Return)): # Doing something else than what we are interested into. return call = statement.value if ( not isinstance(call, nodes.Call) # Not a super() attribute access. or not isinstance(call.func, nodes.Attribute) ): return # Should be a super call. try: super_call = next(call.func.expr.infer()) except astroid.InferenceError: return else: if not isinstance(super_call, astroid.objects.Super): return # The name should be the same. if call.func.attrname != function.name: return # Should be a super call with the MRO pointer being the # current class and the type being the current instance. current_scope = function.parent.scope() if ( super_call.mro_pointer != current_scope or not isinstance(super_call.type, astroid.Instance) or super_call.type.name != current_scope.name ): return # Check values of default args klass = function.parent.frame(future=_True) meth_node = None for overridden in klass.local_attr_ancestors(function.name): # get astroid for the searched method try: meth_node = overridden[function.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if ( not isinstance(meth_node, nodes.FunctionDef) # If the method have an ancestor which is not a # function then it is legitimate to redefine it or _has_different_parameters_default_value( meth_node.args, function.args ) ): return break # Detect if the parameters are the same as the call's arguments. params = _signature_from_arguments(function.args) args = _signature_from_call(call) if meth_node is not None: def form_annotations(arguments): annotations = chain( (arguments.posonlyargs_annotations or []), arguments.annotations ) return [ann.as_string() for ann in annotations if ann is not None] called_annotations = form_annotations(function.args) overridden_annotations = form_annotations(meth_node.args) if called_annotations and overridden_annotations: if called_annotations != overridden_annotations: return if _definition_equivalent_to_call(params, args): self.add_message( "useless-super-delegation", node=function, args=(function.name,) ) def _check_property_with_parameters(self, node): if ( node.args.args and len(node.args.args) > 1 and decorated_with_property(node) and not is_property_setter(node) ): self.add_message("property-with-parameters", node=node) def _check_invalid_overridden_method(self, function_node, parent_function_node): parent_is_property = decorated_with_property( parent_function_node ) or is_property_setter_or_deleter(parent_function_node) current_is_property = decorated_with_property( function_node ) or is_property_setter_or_deleter(function_node) if parent_is_property and not current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "property", function_node.type), node=function_node, ) elif not parent_is_property and current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "method", "property"), node=function_node, ) parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef) current_is_async = isinstance(function_node, nodes.AsyncFunctionDef) if parent_is_async and not current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "async", "non-async"), node=function_node, ) elif not parent_is_async and current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "non-async", "async"), node=function_node, ) if ( decorated_with(parent_function_node, ["typing.final"]) or uninferable_final_decorators(parent_function_node.decorators) ) and self._py38_plus: self.add_message( "overridden-final-method", args=(function_node.name, parent_function_node.parent.frame().name), node=function_node, ) def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,185
is_method
ref
function
not function.is_method()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,212
infer
ref
function
super_call = next(call.func.expr.infer())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,225
scope
ref
function
current_scope = function.parent.scope()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,234
frame
ref
function
klass = function.parent.frame(future=True)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,236
local_attr_ancestors
ref
function
for overridden in klass.local_attr_ancestors(function.name):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,249
_has_different_parameters_default_value
ref
function
or _has_different_parameters_default_value(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,257
_signature_from_arguments
ref
function
params = _signature_from_arguments(function.args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,258
_signature_from_call
ref
function
args = _signature_from_call(call)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,262
form_annotations
def
function
def form_annotations(arguments): annotations = chain( (arguments.posonlyargs_annotations or []), arguments.annotations ) return [ann.as_string() for ann in annotations if ann is not None] called_annotations = form_annotations(function.args) overridden_annotations = form_annotations(meth_node.args) if called_annotations and overridden_annotations: if called_annotations != overridden_annotations: return if _definition_equivalent_to_call(params, args): self.add_message( "useless-super-delegation", node=function, args=(function.name,) ) def _check_property_with_parameters(self, node): if ( node.args.args and len(node.args.args) > 1 and decorated_with_property(node) and not is_property_setter(node) ): self.add_message("property-with-parameters", node=node) def _check_invalid_overridden_method(self, function_node, parent_function_node): parent_is_property = decorated_with_property( parent_function_node ) or is_property_setter_or_deleter(parent_function_node) current_is_property = decorated_with_property( function_node ) or is_property_setter_or_deleter(function_node) if parent_is_property and not current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "property", function_node.type), node=function_node, ) elif not parent_is_property and current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "method", "property"), node=function_node, ) parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef) current_is_async = isinstance(function_node, nodes.AsyncFunctionDef) if parent_is_async and not current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "async", "non-async"), node=function_node, ) elif not parent_is_async and current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "non-async", "async"), node=function_node, ) if ( decorated_with(parent_function_node, ["typing.final"]) or uninferable_final_decorators(parent_function_node.decorators) ) and self._py38_plus: self.add_message( "overridden-final-method", args=(function_node.name, parent_function_node.parent.frame().name), node=function_node, ) def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,266
as_string
ref
function
return [ann.as_string() for ann in annotations if ann is not None]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,268
form_annotations
ref
function
called_annotations = form_annotations(function.args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,269
form_annotations
ref
function
overridden_annotations = form_annotations(meth_node.args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,274
_definition_equivalent_to_call
ref
function
if _definition_equivalent_to_call(params, args):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,275
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,279
_check_property_with_parameters
def
function
def _check_property_with_parameters(self, node): if ( node.args.args and len(node.args.args) > 1 and decorated_with_property(node) and not is_property_setter(node) ): self.add_message("property-with-parameters", node=node) def _check_invalid_overridden_method(self, function_node, parent_function_node): parent_is_property = decorated_with_property( parent_function_node ) or is_property_setter_or_deleter(parent_function_node) current_is_property = decorated_with_property( function_node ) or is_property_setter_or_deleter(function_node) if parent_is_property and not current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "property", function_node.type), node=function_node, ) elif not parent_is_property and current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "method", "property"), node=function_node, ) parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef) current_is_async = isinstance(function_node, nodes.AsyncFunctionDef) if parent_is_async and not current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "async", "non-async"), node=function_node, ) elif not parent_is_async and current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "non-async", "async"), node=function_node, ) if ( decorated_with(parent_function_node, ["typing.final"]) or uninferable_final_decorators(parent_function_node.decorators) ) and self._py38_plus: self.add_message( "overridden-final-method", args=(function_node.name, parent_function_node.parent.frame().name), node=function_node, ) def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,283
decorated_with_property
ref
function
and decorated_with_property(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,284
is_property_setter
ref
function
and not is_property_setter(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,286
add_message
ref
function
self.add_message("property-with-parameters", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,288
_check_invalid_overridden_method
def
function
def _check_invalid_overridden_method(self, function_node, parent_function_node): parent_is_property = decorated_with_property( parent_function_node ) or is_property_setter_or_deleter(parent_function_node) current_is_property = decorated_with_property( function_node ) or is_property_setter_or_deleter(function_node) if parent_is_property and not current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "property", function_node.type), node=function_node, ) elif not parent_is_property and current_is_property: self.add_message( "invalid-overridden-method", args=(function_node.name, "method", "property"), node=function_node, ) parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef) current_is_async = isinstance(function_node, nodes.AsyncFunctionDef) if parent_is_async and not current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "async", "non-async"), node=function_node, ) elif not parent_is_async and current_is_async: self.add_message( "invalid-overridden-method", args=(function_node.name, "non-async", "async"), node=function_node, ) if ( decorated_with(parent_function_node, ["typing.final"]) or uninferable_final_decorators(parent_function_node.decorators) ) and self._py38_plus: self.add_message( "overridden-final-method", args=(function_node.name, parent_function_node.parent.frame().name), node=function_node, ) def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,289
decorated_with_property
ref
function
parent_is_property = decorated_with_property(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,291
is_property_setter_or_deleter
ref
function
) or is_property_setter_or_deleter(parent_function_node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,292
decorated_with_property
ref
function
current_is_property = decorated_with_property(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,294
is_property_setter_or_deleter
ref
function
) or is_property_setter_or_deleter(function_node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,296
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,302
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,312
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,319
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,325
decorated_with
ref
function
decorated_with(parent_function_node, ["typing.final"])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,326
uninferable_final_decorators
ref
function
or uninferable_final_decorators(parent_function_node.decorators)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,328
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,330
frame
ref
function
args=(function_node.name, parent_function_node.parent.frame().name),
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,334
_check_slots
def
function
def _check_slots(self, node: nodes.ClassDef) -> None: if "__slots__" not in node.locals: return for slots in node.igetattr("__slots__"): # check if __slots__ is a valid type if slots is astroid.Uninferable: continue if not is_iterable(slots) and not is_comprehension(slots): self.add_message("invalid-slots", node=node) continue if isinstance(slots, nodes.Const): # a string, ignore the following checks self.add_message("single-string-used-for-slots", node=node) continue if not hasattr(slots, "itered"): # we can't obtain the values, maybe a .deque? continue if isinstance(slots, nodes.Dict): values = [item[0] for item in slots.items] else: values = slots.itered() if values is astroid.Uninferable: return for elt in values: try: self._check_slots_elt(elt, node) except astroid.InferenceError: continue self._check_redefined_slots(node, slots, values) def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,337
igetattr
ref
function
for slots in node.igetattr("__slots__"):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,341
is_iterable
ref
function
if not is_iterable(slots) and not is_comprehension(slots):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,341
is_comprehension
ref
function
if not is_iterable(slots) and not is_comprehension(slots):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,342
add_message
ref
function
self.add_message("invalid-slots", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,347
add_message
ref
function
self.add_message("single-string-used-for-slots", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,356
itered
ref
function
values = slots.itered()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,361
_check_slots_elt
ref
function
self._check_slots_elt(elt, node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,364
_check_redefined_slots
ref
function
self._check_redefined_slots(node, slots, values)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,366
_check_redefined_slots
def
function
def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: """Check if `node` redefines a slot which is defined in an ancestor class.""" slots_names: List[str] = [] for slot in slots_list: if isinstance(slot, nodes.Const): slots_names.append(slot.value) else: inferred_slot = safe_infer(slot) if inferred_slot: slots_names.append(inferred_slot.value) # Slots of all parent classes ancestors_slots_names = { slot.value for ancestor in node.local_attr_ancestors("__slots__") for slot in ancestor.slots() or [] } # Slots which are common to `node` and its parent classes redefined_slots = ancestors_slots_names.intersection(slots_names) if redefined_slots: self.add_message( "redefined-slots-in-subclass", args=([name for name in slots_names if name in redefined_slots],), node=slots_node, ) def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,378
safe_infer
ref
function
inferred_slot = safe_infer(slot)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,385
local_attr_ancestors
ref
function
for ancestor in node.local_attr_ancestors("__slots__")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,386
slots
ref
function
for slot in ancestor.slots() or []
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,393
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,399
_check_slots_elt
def
function
def _check_slots_elt(self, elt, node): for inferred in elt.infer(): if inferred is astroid.Uninferable: continue if not isinstance(inferred, nodes.Const) or not isinstance( inferred.value, str ): self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) continue if not inferred.value: self.add_message( "invalid-slots-object", args=inferred.as_string(), node=elt ) # Check if we have a conflict with a class variable. class_variable = node.locals.get(inferred.value) if class_variable: # Skip annotated assignments which don't conflict at all with slots. if len(class_variable) == 1: parent = class_variable[0].parent if isinstance(parent, nodes.AnnAssign) and parent.value is None: return self.add_message( "class-variable-slots-conflict", args=(inferred.value,), node=elt ) def leave_functiondef(self, node: nodes.FunctionDef) -> None: """On method node, check if this method couldn't be a function. ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"): return class_node = node.parent.frame(future=_True) if ( self._meth_could_be_func and node.type == "method" and node.name not in PYMETHODS and not ( node.is_abstract() or overrides_a_method(class_node, node.name) or decorated_with_property(node) or _has_bare_super_call(node) or is_protocol_class(class_node) or is_overload_stub(node) ) ): self.add_message("no-self-use", node=node) leave_asyncfunctiondef = leave_functiondef def visit_attribute(self, node: nodes.Attribute) -> None: """Check if the getattr is an access to a class member if so, register it. Also check for access to protected class member from outside its class (but ignore __special__ methods) """ # Check self if self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) return if not self.linter.is_message_enabled("protected-access"): return self._check_protected_attribute_access(node) @check_messages("assigning-non-slot", "invalid-class-object") def visit_assignattr(self, node: nodes.AssignAttr) -> None: if isinstance( node.assign_type(), nodes.AugAssign ) and self._uses_mandatory_method_param(node): self._accessed.set_accessed(node) self._check_in_slots(node) self._check_invalid_class_object(node) def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None: if not node.attrname == "__class__": return inferred = safe_infer(node.parent.value) if isinstance(inferred, nodes.ClassDef) or inferred is astroid.Uninferable: # If is uninferrable, we allow it to prevent false positives return self.add_message("invalid-class-object", node=node) def _check_in_slots(self, node): """Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return # If `__setattr__` is defined on the class, then we can't reason about # what will happen when assigning to an attribute. if any( base.locals.get("__setattr__") for base in klass.mro() if base.qname() != "builtins.object" ): return # If 'typing.Generic' is a base of bases of klass, the cached version # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry. if any(base.qname() == "typing.Generic" for base in klass.mro()): cache = getattr(klass, "__cache", None) if cache and cache.get(klass.slots) is not None: del cache[klass.slots] slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass): # Properties circumvent the slots mechanism, # so we should not emit a warning for them. return if node.attrname in klass.locals: for local_name in klass.locals.get(node.attrname): statement = local_name.statement(future=_True) if ( isinstance(statement, nodes.AnnAssign) and not statement.value ): return if _has_data_descriptor(klass, node.attrname): # Descriptors circumvent the slots mechanism as well. return if node.attrname == "__class__" and _has_same_layout_slots( slots, node.parent.value ): return self.add_message("assigning-non-slot", args=(node.attrname,), node=node) @check_messages( "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator" ) def visit_assign(self, assign_node: nodes.Assign) -> None: self._check_classmethod_declaration(assign_node) node = assign_node.targets[0] if not isinstance(node, nodes.AssignAttr): return if self._uses_mandatory_method_param(node): return self._check_protected_attribute_access(node) def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod(). When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, nodes.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, nodes.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, nodes.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, nodes.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0]) def _check_protected_attribute_access(self, node: nodes.Attribute): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # In classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # Typing annotations in function definitions can include protected members if utils.is_node_in_type_annotation_context(node): return # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, nodes.Call) and isinstance(node.expr.func, nodes.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # Check if we are inside the scope of a class or nested inner class inside_klass = _True outer_klass = klass parents_callee = callee.split(".") parents_callee.reverse() for callee in parents_callee: if not outer_klass or callee != outer_klass.name: inside_klass = _False break # Move up one level within the nested classes outer_klass = get_outer_class(outer_klass) # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (inside_klass or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement(future=_True) if ( isinstance(stmt, nodes.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], nodes.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return if ( self._is_classmethod(node.frame(future=_True)) and self._is_inferred_instance(node.expr, klass) and self._is_class_attribute(attrname, klass) ): return licit_protected_member = not attrname.startswith("__") if ( not self.config.check_protected_access_in_special_methods and licit_protected_member and self._is_called_inside_special_method(node) ): return self.add_message("protected-access", node=node, args=attrname) @staticmethod def _is_called_inside_special_method(node: nodes.NodeNG) -> bool: """Returns true if the node is located inside a special (aka dunder) method.""" frame_name = node.frame(future=_True).name return frame_name and frame_name in PYMETHODS def _is_type_self_call(self, expr: nodes.NodeNG) -> bool: return ( isinstance(expr, nodes.Call) and isinstance(expr.func, nodes.Name) and expr.func.name == "type" and len(expr.args) == 1 and self._is_mandatory_method_param(expr.args[0]) ) @staticmethod def _is_classmethod(func): """Check if the given *func* node is a class method.""" return isinstance(func, nodes.FunctionDef) and ( func.type == "classmethod" or func.name == "__class_getitem__" ) @staticmethod def _is_inferred_instance(expr, klass): """Check if the inferred value of the given *expr* is an instance of *klass*.""" inferred = safe_infer(expr) if not isinstance(inferred, astroid.Instance): return _False return inferred._proxied is klass @staticmethod def _is_class_attribute(name, klass): """Check if the given attribute *name* is a class or instance member of the given *klass*. Returns ``_True`` if the name is a property in the given klass, ``_False`` otherwise. """ try: klass.getattr(name) return _True except astroid.NotFoundError: pass try: klass.instance_attr(name) return _True except astroid.NotFoundError: return _False def visit_name(self, node: nodes.Name) -> None: """Check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = _False def _check_accessed_members(self, node, accessed): """Check that accessed members are defined.""" excs = ("AttributeError", "Exception", "BaseException") for attr, nodes_lst in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame(future=_True) lno = defstmt.fromlineno for _node in nodes_lst: if ( _node.frame(future=_True) is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(future=_True), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), ) def _check_first_arg_for_type(self, node, metaclass=0): """Check the name of first argument, expect:. * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return if node.args.posonlyargs: first_arg = node.args.posonlyargs[0].name elif node.args.args: first_arg = node.argnames()[0] else: first_arg = None self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args and not node.args.posonlyargs: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class with class method elif node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular class with regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node) def _check_first_arg_config(self, first, config, node, message, method_name): if first not in config: if len(config) == 1: valid = repr(config[0]) else: valid = ", ".join(repr(v) for v in config[:-1]) valid = f"{valid} or {config[-1]!r}" self.add_message(message, args=(method_name, valid), node=node) def _check_bases_classes(self, node): """Check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=_False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame(future=_True) if owner is node: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name)) def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None: """Check that the __init__ method call super or ancestors'__init__ method (unless it is used for type hinting with `typing.overload`) """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) parents_with_called_inits: Set[bases.UnboundMethod] = set() for stmt in node.nodes_of_class(nodes.Call): expr = stmt.func if not isinstance(expr, nodes.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, nodes.Call) and isinstance(expr.expr.func, nodes.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The inferred klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, nodes.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, astroid.objects.Super): return try: method = not_called_yet.pop(klass) # Record that the class' init has been called parents_with_called_inits.add(node_frame_class(method)) except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): # Check if the init of the class that defines this init has already # been called. if node_frame_class(method) in parents_with_called_inits: return # Return if klass is protocol if klass.qname() in utils.TYPING_PROTOCOLS: return # Return if any of the klass' first-order bases is protocol for base in klass.bases: # We don't need to catch InferenceError here as _ancestors_to_call # already does this for us. for inf_base in base.infer(): if inf_base.qname() in utils.TYPING_PROTOCOLS: return if decorated_with(node, ["typing.overload"]): continue cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message( "super-init-not-called", args=klass.name, node=node, confidence=INFERENCE, ) def _check_signature(self, method1, refmethod, class_type, cls): """Check that the signature of the two given methods match.""" if not ( isinstance(method1, nodes.FunctionDef) and isinstance(refmethod, nodes.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = astroid.scoped_nodes.function_to_method(method1, instance) refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if is_property_setter(method1): return arg_differ_output = _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ) if len(arg_differ_output) > 0: for msg in arg_differ_output: if "Number" in msg: total_args_method1 = len(method1.args.args) if method1.args.vararg: total_args_method1 += 1 if method1.args.kwarg: total_args_method1 += 1 if method1.args.kwonlyargs: total_args_method1 += len(method1.args.kwonlyargs) total_args_refmethod = len(refmethod.args.args) if refmethod.args.vararg: total_args_refmethod += 1 if refmethod.args.kwarg: total_args_refmethod += 1 if refmethod.args.kwonlyargs: total_args_refmethod += len(refmethod.args.kwonlyargs) error_type = "arguments-differ" msg_args = ( msg + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and " f"is now {total_args_method1} in", class_type, f"{method1.parent.frame().name}.{method1.name}", ) elif "renamed" in msg: error_type = "arguments-renamed" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) else: error_type = "arguments-differ" msg_args = ( msg, class_type, f"{method1.parent.frame().name}.{method1.name}", ) self.add_message(error_type, args=msg_args, node=method1) elif ( len(method1.args.defaults) < len(refmethod.args.defaults) and not method1.args.vararg ): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 ) def _uses_mandatory_method_param(self, node): """Check that attribute lookup name use first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return self._is_mandatory_method_param(node.expr) def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool: """Check if nodes.Name corresponds to first attribute variable name. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ if self._first_attrs: first_attr = self._first_attrs[-1] else: # It's possible the function was already unregistered. closest_func = utils.get_node_first_ancestor_of_type( node, nodes.FunctionDef ) if closest_func is None: return _False if not closest_func.args.args: return _False first_attr = closest_func.args.args[0].name return isinstance(node, nodes.Name) and node.name == first_attr
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,400
infer
ref
function
for inferred in elt.infer():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py
pylint/checkers/classes/class_checker.py
1,406
add_message
ref
function
self.add_message(