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 | 1,407 | as_string | ref | function | "invalid-slots-object", args=inferred.as_string(), node=elt
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,411 | 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,412 | as_string | ref | function | "invalid-slots-object", args=inferred.as_string(), node=elt
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,423 | 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,427 | leave_functiondef | def | function | 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,433 | is_method | ref | function | if node.is_method():
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,436 | is_message_enabled | ref | function | if not self.linter.is_message_enabled("no-self-use"):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,438 | frame | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,444 | is_abstract | ref | function | node.is_abstract()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,445 | overrides_a_method | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,446 | decorated_with_property | ref | function | or decorated_with_property(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,447 | _has_bare_super_call | ref | function | or _has_bare_super_call(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,448 | is_protocol_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,449 | is_overload_stub | ref | function | or is_overload_stub(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,452 | add_message | ref | function | self.add_message("no-self-use", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,456 | visit_attribute | def | function | 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,463 | _uses_mandatory_method_param | ref | function | if self._uses_mandatory_method_param(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,464 | set_accessed | ref | function | self._accessed.set_accessed(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,466 | is_message_enabled | ref | function | if not self.linter.is_message_enabled("protected-access"):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,469 | _check_protected_attribute_access | ref | function | self._check_protected_attribute_access(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,471 | check_messages | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,472 | visit_assignattr | def | function | 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,474 | assign_type | ref | function | node.assign_type(), nodes.AugAssign
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,475 | _uses_mandatory_method_param | ref | function | ) and self._uses_mandatory_method_param(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,476 | set_accessed | ref | function | self._accessed.set_accessed(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,477 | _check_in_slots | ref | function | self._check_in_slots(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,478 | _check_invalid_class_object | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,480 | _check_invalid_class_object | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,483 | safe_infer | ref | function | inferred = safe_infer(node.parent.value)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,487 | add_message | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,489 | _check_in_slots | def | function | 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,493 | safe_infer | ref | function | inferred = safe_infer(node.expr)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,498 | has_known_bases | ref | function | if not has_known_bases(klass):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,506 | mro | ref | function | for base in klass.mro()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,507 | qname | ref | function | if base.qname() != "builtins.object"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,513 | qname | ref | function | if any(base.qname() == "typing.Generic" for base in klass.mro()):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,513 | mro | ref | function | if any(base.qname() == "typing.Generic" for base in klass.mro()):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,518 | slots | ref | function | slots = klass.slots()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,525 | 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,533 | _is_attribute_property | ref | function | if _is_attribute_property(node.attrname, klass):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,539 | statement | ref | function | statement = local_name.statement(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,545 | _has_data_descriptor | ref | function | if _has_data_descriptor(klass, node.attrname):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,548 | _has_same_layout_slots | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,552 | add_message | ref | function | self.add_message("assigning-non-slot", args=(node.attrname,), node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,554 | check_messages | ref | function | @check_messages(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,557 | visit_assign | def | function | 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,558 | _check_classmethod_declaration | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,563 | _uses_mandatory_method_param | ref | function | if self._uses_mandatory_method_param(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,565 | _check_protected_attribute_access | ref | function | self._check_protected_attribute_access(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,567 | _check_classmethod_declaration | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,593 | scope | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,603 | mymethods | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,604 | add_message | ref | function | self.add_message(msg, node=node.targets[0])
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,606 | _check_protected_attribute_access | def | function | 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,619 | is_attr_protected | ref | function | is_attr_protected(attrname)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,623 | node_frame_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,627 | as_string | ref | function | callee = node.expr.as_string()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,630 | is_node_in_type_annotation_context | ref | function | if utils.is_node_in_type_annotation_context(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,635 | add_message | ref | function | self.add_message("protected-access", node=node, args=attrname)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,647 | _is_type_self_call | ref | function | if self._is_type_self_call(node.expr):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,661 | get_outer_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,672 | statement | ref | function | stmt = node.parent.statement(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,679 | _is_attribute_property | ref | function | if _is_attribute_property(name, klass):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,683 | _is_classmethod | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,683 | frame | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,684 | _is_inferred_instance | ref | function | and self._is_inferred_instance(node.expr, klass)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,685 | _is_class_attribute | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,693 | _is_called_inside_special_method | ref | function | and self._is_called_inside_special_method(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,697 | add_message | ref | function | self.add_message("protected-access", node=node, args=attrname)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,700 | _is_called_inside_special_method | def | function | 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,702 | frame | ref | function | frame_name = node.frame(future=True).name
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,705 | _is_type_self_call | def | function | 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,711 | _is_mandatory_method_param | ref | function | and self._is_mandatory_method_param(expr.args[0])
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,715 | _is_classmethod | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,723 | _is_inferred_instance | def | function | 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,726 | safe_infer | ref | function | inferred = safe_infer(expr)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,733 | _is_class_attribute | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,747 | instance_attr | ref | function | klass.instance_attr(name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,752 | visit_name | def | function | 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,761 | _check_accessed_members | def | function | 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,767 | local_attr | ref | function | node.local_attr(attr)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,774 | instance_attr_ancestors | ref | function | next(node.instance_attr_ancestors(attr))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,781 | instance_attr | ref | function | defstmts = node.instance_attr(attr)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,793 | scope | ref | function | scope = defstmts[0].scope()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,797 | scope | ref | function | if i == 0 or stmt.scope() is not scope
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,805 | frame | ref | function | frame = defstmt.frame(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,809 | frame | ref | function | _node.frame(future=True) is frame
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,811 | are_exclusive | ref | function | and not astroid.are_exclusive(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,812 | statement | ref | function | _node.statement(future=True), defstmt, excs
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,815 | 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,821 | _check_first_arg_for_type | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,837 | argnames | ref | function | first_arg = node.argnames()[0]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,849 | add_message | ref | function | self.add_message("bad-staticmethod-argument", args=first, node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,854 | add_message | ref | function | self.add_message("no-method-argument", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,859 | _check_first_arg_config | ref | function | self._check_first_arg_config(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,868 | _check_first_arg_config | ref | function | self._check_first_arg_config(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,877 | _check_first_arg_config | ref | function | self._check_first_arg_config(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,886 | add_message | ref | function | self.add_message("no-self-argument", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/class_checker.py | pylint/checkers/classes/class_checker.py | 1,888 | _check_first_arg_config | def | function | 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,895 | add_message | ref | function | self.add_message(message, args=(method_name, valid), node=node)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.