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/variables.py | pylint/checkers/variables.py | 2,309 | _check_unused_arguments | ref | function | self._check_unused_arguments(name, node, stmt, argnames)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,330 | _has_locals_call_after_node | ref | function | if _has_locals_call_after_node(stmt, node.scope()):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,330 | scope | ref | function | if _has_locals_call_after_node(stmt, node.scope()):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,338 | add_message | ref | function | self.add_message("unused-import", args=msg, node=stmt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,345 | add_message | ref | function | self.add_message("unused-import", args=msg, node=stmt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,353 | is_overload_stub | ref | function | if utils.is_overload_stub(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,358 | nodes_of_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,362 | add_message | ref | function | self.add_message(message_name, args=name, node=stmt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,364 | _is_name_ignored | def | function | def _is_name_ignored(self, stmt, name):
authorized_rgx = self.config.dummy_variables_rgx
if (
isinstance(stmt, nodes.AssignName)
and isinstance(stmt.parent, nodes.Arguments)
or isinstance(stmt, nodes.Arguments)
):
regex = self.config.ignored_argument_names
else:
regex = authorized_rgx
return regex and regex.match(name)
def _check_unused_arguments(self, name, node, stmt, argnames):
is_method = node.is_method()
klass = node.parent.frame(future=_True)
if is_method and isinstance(klass, nodes.ClassDef):
confidence = (
INFERENCE if utils.has_known_bases(klass) else INFERENCE_FAILURE
)
else:
confidence = HIGH
if is_method:
# Don't warn for the first argument of a (non static) method
if node.type != "staticmethod" and name == argnames[0]:
return
# Don't warn for argument of an overridden method
overridden = overridden_method(klass, node.name)
if overridden is not None and name in overridden.argnames():
return
if node.name in utils.PYMETHODS and node.name not in (
"__init__",
"__new__",
):
return
# Don't check callback arguments
if any(
node.name.startswith(cb) or node.name.endswith(cb)
for cb in self.config.callbacks
):
return
# Don't check arguments of singledispatch.register function.
if utils.is_registered_in_singledispatch_function(node):
return
# Don't check function stubs created only for type information
if utils.is_overload_stub(node):
return
# Don't check protocol classes
if utils.is_protocol_class(klass):
return
self.add_message("unused-argument", args=name, node=stmt, confidence=confidence)
def _check_late_binding_closure(self, node: nodes.Name) -> None:
"""Check whether node is a cell var that is assigned within a containing loop.
Special cases where we don't care about the error:
1. When the node's function is immediately called, e.g. (lambda: i)()
2. When the node's function is returned from within the loop, e.g. return lambda: i
"""
if not self.linter.is_message_enabled("cell-var-from-loop"):
return
node_scope = node.frame(future=_True)
# If node appears in a default argument expression,
# look at the next enclosing frame instead
if utils.is_default_argument(node, node_scope):
node_scope = node_scope.parent.frame(future=_True)
# Check if node is a cell var
if (
not isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef))
or node.name in node_scope.locals
):
return
assign_scope, stmts = node.lookup(node.name)
if not stmts or not assign_scope.parent_of(node_scope):
return
if utils.is_comprehension(assign_scope):
self.add_message("cell-var-from-loop", node=node, args=node.name)
else:
# Look for an enclosing For loop.
# Currently, we only consider the first assignment
assignment_node = stmts[0]
maybe_for = assignment_node
while maybe_for and not isinstance(maybe_for, nodes.For):
if maybe_for is assign_scope:
break
maybe_for = maybe_for.parent
else:
if (
maybe_for
and maybe_for.parent_of(node_scope)
and not utils.is_being_called(node_scope)
and node_scope.parent
and not isinstance(node_scope.statement(future=_True), nodes.Return)
):
self.add_message("cell-var-from-loop", node=node, args=node.name)
def _should_ignore_redefined_builtin(self, stmt):
if not isinstance(stmt, nodes.ImportFrom):
return _False
return stmt.modname in self.config.redefining_builtins_modules
def _allowed_redefined_builtin(self, name):
return name in self.config.allowed_redefined_builtins
def _has_homonym_in_upper_function_scope(
self, node: nodes.Name, index: int
) -> bool:
"""Return whether there is a node with the same name in the
to_consume dict of an upper scope and if that scope is a
function
:param node: node to check for
:param index: index of the current consumer inside self._to_consume
:return: _True if there is a node with the same name in the
to_consume dict of an upper scope and if that scope
is a function, _False otherwise
"""
return any(
_consumer.scope_type == "function" and node.name in _consumer.to_consume
for _consumer in self._to_consume[index - 1 :: -1]
)
def _store_type_annotation_node(self, type_annotation):
"""Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
if isinstance(type_annotation, nodes.Attribute):
self._store_type_annotation_node(type_annotation.expr)
return
if not isinstance(type_annotation, nodes.Subscript):
return
if (
isinstance(type_annotation.value, nodes.Attribute)
and isinstance(type_annotation.value.expr, nodes.Name)
and type_annotation.value.expr.name == TYPING_MODULE
):
self._type_annotation_names.append(TYPING_MODULE)
return
self._type_annotation_names.extend(
annotation.name for annotation in type_annotation.nodes_of_class(nodes.Name)
)
def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,376 | _check_unused_arguments | def | function | def _check_unused_arguments(self, name, node, stmt, argnames):
is_method = node.is_method()
klass = node.parent.frame(future=_True)
if is_method and isinstance(klass, nodes.ClassDef):
confidence = (
INFERENCE if utils.has_known_bases(klass) else INFERENCE_FAILURE
)
else:
confidence = HIGH
if is_method:
# Don't warn for the first argument of a (non static) method
if node.type != "staticmethod" and name == argnames[0]:
return
# Don't warn for argument of an overridden method
overridden = overridden_method(klass, node.name)
if overridden is not None and name in overridden.argnames():
return
if node.name in utils.PYMETHODS and node.name not in (
"__init__",
"__new__",
):
return
# Don't check callback arguments
if any(
node.name.startswith(cb) or node.name.endswith(cb)
for cb in self.config.callbacks
):
return
# Don't check arguments of singledispatch.register function.
if utils.is_registered_in_singledispatch_function(node):
return
# Don't check function stubs created only for type information
if utils.is_overload_stub(node):
return
# Don't check protocol classes
if utils.is_protocol_class(klass):
return
self.add_message("unused-argument", args=name, node=stmt, confidence=confidence)
def _check_late_binding_closure(self, node: nodes.Name) -> None:
"""Check whether node is a cell var that is assigned within a containing loop.
Special cases where we don't care about the error:
1. When the node's function is immediately called, e.g. (lambda: i)()
2. When the node's function is returned from within the loop, e.g. return lambda: i
"""
if not self.linter.is_message_enabled("cell-var-from-loop"):
return
node_scope = node.frame(future=_True)
# If node appears in a default argument expression,
# look at the next enclosing frame instead
if utils.is_default_argument(node, node_scope):
node_scope = node_scope.parent.frame(future=_True)
# Check if node is a cell var
if (
not isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef))
or node.name in node_scope.locals
):
return
assign_scope, stmts = node.lookup(node.name)
if not stmts or not assign_scope.parent_of(node_scope):
return
if utils.is_comprehension(assign_scope):
self.add_message("cell-var-from-loop", node=node, args=node.name)
else:
# Look for an enclosing For loop.
# Currently, we only consider the first assignment
assignment_node = stmts[0]
maybe_for = assignment_node
while maybe_for and not isinstance(maybe_for, nodes.For):
if maybe_for is assign_scope:
break
maybe_for = maybe_for.parent
else:
if (
maybe_for
and maybe_for.parent_of(node_scope)
and not utils.is_being_called(node_scope)
and node_scope.parent
and not isinstance(node_scope.statement(future=_True), nodes.Return)
):
self.add_message("cell-var-from-loop", node=node, args=node.name)
def _should_ignore_redefined_builtin(self, stmt):
if not isinstance(stmt, nodes.ImportFrom):
return _False
return stmt.modname in self.config.redefining_builtins_modules
def _allowed_redefined_builtin(self, name):
return name in self.config.allowed_redefined_builtins
def _has_homonym_in_upper_function_scope(
self, node: nodes.Name, index: int
) -> bool:
"""Return whether there is a node with the same name in the
to_consume dict of an upper scope and if that scope is a
function
:param node: node to check for
:param index: index of the current consumer inside self._to_consume
:return: _True if there is a node with the same name in the
to_consume dict of an upper scope and if that scope
is a function, _False otherwise
"""
return any(
_consumer.scope_type == "function" and node.name in _consumer.to_consume
for _consumer in self._to_consume[index - 1 :: -1]
)
def _store_type_annotation_node(self, type_annotation):
"""Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
if isinstance(type_annotation, nodes.Attribute):
self._store_type_annotation_node(type_annotation.expr)
return
if not isinstance(type_annotation, nodes.Subscript):
return
if (
isinstance(type_annotation.value, nodes.Attribute)
and isinstance(type_annotation.value.expr, nodes.Name)
and type_annotation.value.expr.name == TYPING_MODULE
):
self._type_annotation_names.append(TYPING_MODULE)
return
self._type_annotation_names.extend(
annotation.name for annotation in type_annotation.nodes_of_class(nodes.Name)
)
def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,377 | is_method | ref | function | is_method = node.is_method()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,378 | frame | ref | function | klass = node.parent.frame(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,381 | has_known_bases | ref | function | INFERENCE if utils.has_known_bases(klass) else INFERENCE_FAILURE
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,391 | overridden_method | ref | function | overridden = overridden_method(klass, node.name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,392 | argnames | ref | function | if overridden is not None and name in overridden.argnames():
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,406 | is_registered_in_singledispatch_function | ref | function | if utils.is_registered_in_singledispatch_function(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,410 | is_overload_stub | ref | function | if utils.is_overload_stub(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,414 | is_protocol_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,417 | add_message | ref | function | self.add_message("unused-argument", args=name, node=stmt, confidence=confidence)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,419 | _check_late_binding_closure | def | function | def _check_late_binding_closure(self, node: nodes.Name) -> None:
"""Check whether node is a cell var that is assigned within a containing loop.
Special cases where we don't care about the error:
1. When the node's function is immediately called, e.g. (lambda: i)()
2. When the node's function is returned from within the loop, e.g. return lambda: i
"""
if not self.linter.is_message_enabled("cell-var-from-loop"):
return
node_scope = node.frame(future=_True)
# If node appears in a default argument expression,
# look at the next enclosing frame instead
if utils.is_default_argument(node, node_scope):
node_scope = node_scope.parent.frame(future=_True)
# Check if node is a cell var
if (
not isinstance(node_scope, (nodes.Lambda, nodes.FunctionDef))
or node.name in node_scope.locals
):
return
assign_scope, stmts = node.lookup(node.name)
if not stmts or not assign_scope.parent_of(node_scope):
return
if utils.is_comprehension(assign_scope):
self.add_message("cell-var-from-loop", node=node, args=node.name)
else:
# Look for an enclosing For loop.
# Currently, we only consider the first assignment
assignment_node = stmts[0]
maybe_for = assignment_node
while maybe_for and not isinstance(maybe_for, nodes.For):
if maybe_for is assign_scope:
break
maybe_for = maybe_for.parent
else:
if (
maybe_for
and maybe_for.parent_of(node_scope)
and not utils.is_being_called(node_scope)
and node_scope.parent
and not isinstance(node_scope.statement(future=_True), nodes.Return)
):
self.add_message("cell-var-from-loop", node=node, args=node.name)
def _should_ignore_redefined_builtin(self, stmt):
if not isinstance(stmt, nodes.ImportFrom):
return _False
return stmt.modname in self.config.redefining_builtins_modules
def _allowed_redefined_builtin(self, name):
return name in self.config.allowed_redefined_builtins
def _has_homonym_in_upper_function_scope(
self, node: nodes.Name, index: int
) -> bool:
"""Return whether there is a node with the same name in the
to_consume dict of an upper scope and if that scope is a
function
:param node: node to check for
:param index: index of the current consumer inside self._to_consume
:return: _True if there is a node with the same name in the
to_consume dict of an upper scope and if that scope
is a function, _False otherwise
"""
return any(
_consumer.scope_type == "function" and node.name in _consumer.to_consume
for _consumer in self._to_consume[index - 1 :: -1]
)
def _store_type_annotation_node(self, type_annotation):
"""Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
if isinstance(type_annotation, nodes.Attribute):
self._store_type_annotation_node(type_annotation.expr)
return
if not isinstance(type_annotation, nodes.Subscript):
return
if (
isinstance(type_annotation.value, nodes.Attribute)
and isinstance(type_annotation.value.expr, nodes.Name)
and type_annotation.value.expr.name == TYPING_MODULE
):
self._type_annotation_names.append(TYPING_MODULE)
return
self._type_annotation_names.extend(
annotation.name for annotation in type_annotation.nodes_of_class(nodes.Name)
)
def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,426 | is_message_enabled | ref | function | if not self.linter.is_message_enabled("cell-var-from-loop"):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,429 | frame | ref | function | node_scope = node.frame(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,433 | is_default_argument | ref | function | if utils.is_default_argument(node, node_scope):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,434 | frame | ref | function | node_scope = node_scope.parent.frame(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,443 | lookup | ref | function | assign_scope, stmts = node.lookup(node.name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,444 | parent_of | ref | function | if not stmts or not assign_scope.parent_of(node_scope):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,447 | is_comprehension | ref | function | if utils.is_comprehension(assign_scope):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,448 | add_message | ref | function | self.add_message("cell-var-from-loop", node=node, args=node.name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,462 | parent_of | ref | function | and maybe_for.parent_of(node_scope)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,463 | is_being_called | ref | function | and not utils.is_being_called(node_scope)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,465 | statement | ref | function | and not isinstance(node_scope.statement(future=True), nodes.Return)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,467 | add_message | ref | function | self.add_message("cell-var-from-loop", node=node, args=node.name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,469 | _should_ignore_redefined_builtin | def | function | def _should_ignore_redefined_builtin(self, stmt):
if not isinstance(stmt, nodes.ImportFrom):
return _False
return stmt.modname in self.config.redefining_builtins_modules
def _allowed_redefined_builtin(self, name):
return name in self.config.allowed_redefined_builtins
def _has_homonym_in_upper_function_scope(
self, node: nodes.Name, index: int
) -> bool:
"""Return whether there is a node with the same name in the
to_consume dict of an upper scope and if that scope is a
function
:param node: node to check for
:param index: index of the current consumer inside self._to_consume
:return: _True if there is a node with the same name in the
to_consume dict of an upper scope and if that scope
is a function, _False otherwise
"""
return any(
_consumer.scope_type == "function" and node.name in _consumer.to_consume
for _consumer in self._to_consume[index - 1 :: -1]
)
def _store_type_annotation_node(self, type_annotation):
"""Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
if isinstance(type_annotation, nodes.Attribute):
self._store_type_annotation_node(type_annotation.expr)
return
if not isinstance(type_annotation, nodes.Subscript):
return
if (
isinstance(type_annotation.value, nodes.Attribute)
and isinstance(type_annotation.value.expr, nodes.Name)
and type_annotation.value.expr.name == TYPING_MODULE
):
self._type_annotation_names.append(TYPING_MODULE)
return
self._type_annotation_names.extend(
annotation.name for annotation in type_annotation.nodes_of_class(nodes.Name)
)
def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,474 | _allowed_redefined_builtin | def | function | def _allowed_redefined_builtin(self, name):
return name in self.config.allowed_redefined_builtins
def _has_homonym_in_upper_function_scope(
self, node: nodes.Name, index: int
) -> bool:
"""Return whether there is a node with the same name in the
to_consume dict of an upper scope and if that scope is a
function
:param node: node to check for
:param index: index of the current consumer inside self._to_consume
:return: _True if there is a node with the same name in the
to_consume dict of an upper scope and if that scope
is a function, _False otherwise
"""
return any(
_consumer.scope_type == "function" and node.name in _consumer.to_consume
for _consumer in self._to_consume[index - 1 :: -1]
)
def _store_type_annotation_node(self, type_annotation):
"""Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
if isinstance(type_annotation, nodes.Attribute):
self._store_type_annotation_node(type_annotation.expr)
return
if not isinstance(type_annotation, nodes.Subscript):
return
if (
isinstance(type_annotation.value, nodes.Attribute)
and isinstance(type_annotation.value.expr, nodes.Name)
and type_annotation.value.expr.name == TYPING_MODULE
):
self._type_annotation_names.append(TYPING_MODULE)
return
self._type_annotation_names.extend(
annotation.name for annotation in type_annotation.nodes_of_class(nodes.Name)
)
def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,477 | _has_homonym_in_upper_function_scope | def | function | def _has_homonym_in_upper_function_scope(
self, node: nodes.Name, index: int
) -> bool:
"""Return whether there is a node with the same name in the
to_consume dict of an upper scope and if that scope is a
function
:param node: node to check for
:param index: index of the current consumer inside self._to_consume
:return: _True if there is a node with the same name in the
to_consume dict of an upper scope and if that scope
is a function, _False otherwise
"""
return any(
_consumer.scope_type == "function" and node.name in _consumer.to_consume
for _consumer in self._to_consume[index - 1 :: -1]
)
def _store_type_annotation_node(self, type_annotation):
"""Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
if isinstance(type_annotation, nodes.Attribute):
self._store_type_annotation_node(type_annotation.expr)
return
if not isinstance(type_annotation, nodes.Subscript):
return
if (
isinstance(type_annotation.value, nodes.Attribute)
and isinstance(type_annotation.value.expr, nodes.Name)
and type_annotation.value.expr.name == TYPING_MODULE
):
self._type_annotation_names.append(TYPING_MODULE)
return
self._type_annotation_names.extend(
annotation.name for annotation in type_annotation.nodes_of_class(nodes.Name)
)
def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,495 | _store_type_annotation_node | def | function | def _store_type_annotation_node(self, type_annotation):
"""Given a type annotation, store all the name nodes it refers to."""
if isinstance(type_annotation, nodes.Name):
self._type_annotation_names.append(type_annotation.name)
return
if isinstance(type_annotation, nodes.Attribute):
self._store_type_annotation_node(type_annotation.expr)
return
if not isinstance(type_annotation, nodes.Subscript):
return
if (
isinstance(type_annotation.value, nodes.Attribute)
and isinstance(type_annotation.value.expr, nodes.Name)
and type_annotation.value.expr.name == TYPING_MODULE
):
self._type_annotation_names.append(TYPING_MODULE)
return
self._type_annotation_names.extend(
annotation.name for annotation in type_annotation.nodes_of_class(nodes.Name)
)
def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,502 | _store_type_annotation_node | ref | function | self._store_type_annotation_node(type_annotation.expr)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,517 | nodes_of_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,520 | _store_type_annotation_names | def | function | def _store_type_annotation_names(self, node):
type_annotation = node.type_annotation
if not type_annotation:
return
self._store_type_annotation_node(node.type_annotation)
def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,524 | _store_type_annotation_node | ref | function | self._store_type_annotation_node(node.type_annotation)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,526 | _check_self_cls_assign | def | function | def _check_self_cls_assign(self, node: nodes.Assign) -> None:
"""Check that self/cls don't get assigned."""
assign_names: Set[Optional[str]] = set()
for target in node.targets:
if isinstance(target, nodes.AssignName):
assign_names.add(target.name)
elif isinstance(target, nodes.Tuple):
assign_names.update(
elt.name for elt in target.elts if isinstance(elt, nodes.AssignName)
)
scope = node.scope()
nonlocals_with_same_name = any(
child for child in scope.body if isinstance(child, nodes.Nonlocal)
)
if nonlocals_with_same_name:
scope = node.scope().parent.scope()
if not (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and "builtins.staticmethod" not in scope.decoratornames()
):
return
argument_names = scope.argnames()
if not argument_names:
return
self_cls_name = argument_names[0]
if self_cls_name in assign_names:
self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,536 | scope | ref | function | scope = node.scope()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,541 | scope | ref | function | scope = node.scope().parent.scope()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,541 | scope | ref | function | scope = node.scope().parent.scope()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,545 | is_method | ref | function | and scope.is_method()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,546 | decoratornames | ref | function | and "builtins.staticmethod" not in scope.decoratornames()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,549 | argnames | ref | function | argument_names = scope.argnames()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,554 | add_message | ref | function | self.add_message("self-cls-assignment", node=node, args=(self_cls_name,))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,556 | _check_unpacking | def | function | def _check_unpacking(self, inferred, node, targets):
"""Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if inferred is astroid.Uninferable:
return
if (
isinstance(inferred.parent, nodes.Arguments)
and isinstance(node.value, nodes.Name)
and node.value.name == inferred.parent.vararg
):
# Variable-length argument, we can't determine the length.
return
# Attempt to check unpacking is properly balanced
values = self._nodes_to_unpack(inferred)
if values is not None:
if len(targets) != len(values):
# Check if we have starred nodes.
if any(isinstance(target, nodes.Starred) for target in targets):
return
self.add_message(
"unbalanced-tuple-unpacking",
node=node,
args=(
_get_unpacking_extra_info(node, inferred),
len(targets),
len(values),
),
)
# attempt to check unpacking may be possible (ie RHS is iterable)
elif not utils.is_iterable(inferred):
self.add_message(
"unpacking-non-sequence",
node=node,
args=(_get_unpacking_extra_info(node, inferred),),
)
@staticmethod
def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,560 | is_inside_abstract_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,562 | is_comprehension | ref | function | if utils.is_comprehension(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,575 | _nodes_to_unpack | ref | function | values = self._nodes_to_unpack(inferred)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,581 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,585 | _get_unpacking_extra_info | ref | function | _get_unpacking_extra_info(node, inferred),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,591 | is_iterable | ref | function | elif not utils.is_iterable(inferred):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,592 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,595 | _get_unpacking_extra_info | ref | function | args=(_get_unpacking_extra_info(node, inferred),),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,599 | _nodes_to_unpack | def | function | def _nodes_to_unpack(node: nodes.NodeNG) -> Optional[List[nodes.NodeNG]]:
"""Return the list of values of the `Assign` node."""
if isinstance(node, (nodes.Tuple, nodes.List)):
return node.itered()
if isinstance(node, astroid.Instance) and any(
ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
):
return [i for i in node.values() if isinstance(i, nodes.AssignName)]
return None
def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,602 | itered | ref | function | return node.itered()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,604 | qname | ref | function | ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,604 | ancestors | ref | function | ancestor.qname() == "typing.NamedTuple" for ancestor in node.ancestors()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,609 | _check_module_attrs | def | function | def _check_module_attrs(self, node, module, module_names):
"""Check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
while module_names:
name = module_names.pop(0)
if name == "__dict__":
module = None
break
try:
module = next(module.getattr(name)[0].infer())
if module is astroid.Uninferable:
return None
except astroid.NotFoundError:
if module.name in self._ignored_modules:
return None
self.add_message(
"no-name-in-module", args=(name, module.name), node=node
)
return None
except astroid.InferenceError:
return None
if module_names:
modname = module.name if module else "__dict__"
self.add_message(
"no-name-in-module", node=node, args=(".".join(module_names), modname)
)
return None
if isinstance(module, nodes.Module):
return module
return None
def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,620 | infer | ref | function | module = next(module.getattr(name)[0].infer())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,626 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,634 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,642 | _check_all | def | function | def _check_all(self, node: nodes.Module, not_consumed):
assigned = next(node.igetattr("__all__"))
if assigned is astroid.Uninferable:
return
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
line, col = assigned.tolineno, assigned.col_offset
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
return
for elt in getattr(assigned, "elts", ()):
try:
elt_name = next(elt.infer())
except astroid.InferenceError:
continue
if elt_name is astroid.Uninferable:
continue
if not elt_name.parent:
continue
if not isinstance(elt_name, nodes.Const) or not isinstance(
elt_name.value, str
):
self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
continue
elt_name = elt_name.value
# If elt is in not_consumed, remove it from not_consumed
if elt_name in not_consumed:
del not_consumed[elt_name]
continue
if elt_name not in node.locals:
if not node.package:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
else:
basename = os.path.splitext(node.file)[0]
if os.path.basename(basename) == "__init__":
name = node.name + "." + elt_name
try:
astroid.modutils.file_from_modpath(name.split("."))
except ImportError:
self.add_message(
"undefined-all-variable", args=(elt_name,), node=elt
)
except SyntaxError:
# don't yield a syntax-error warning,
# because it will be later yielded
# when the file will be checked
pass
def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,643 | igetattr | ref | function | assigned = next(node.igetattr("__all__"))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,646 | pytype | ref | function | if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,648 | add_message | ref | function | self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,652 | infer | ref | function | elt_name = next(elt.infer())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,663 | add_message | ref | function | self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,663 | as_string | ref | function | self.add_message("invalid-all-object", args=elt.as_string(), node=elt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,674 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,678 | splitext | ref | function | basename = os.path.splitext(node.file)[0]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,679 | basename | ref | function | if os.path.basename(basename) == "__init__":
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,682 | file_from_modpath | ref | function | astroid.modutils.file_from_modpath(name.split("."))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,684 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,693 | _check_globals | def | function | def _check_globals(self, not_consumed):
if self._allow_global_unused_variables:
return
for name, node_lst in not_consumed.items():
for node in node_lst:
self.add_message("unused-variable", args=(name,), node=node)
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,698 | add_message | ref | function | self.add_message("unused-variable", args=(name,), node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,700 | _check_imports | def | function | def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
Tuple[str, nodes.ImportFrom], List[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
for imports in stmt.names:
real_name = imported_name = imports[0]
if imported_name == "*":
real_name = name
as_name = imports[1]
if real_name in checked:
continue
if name not in (real_name, as_name):
continue
checked.add(real_name)
is_type_annotation_import = (
imported_name in self._type_annotation_names
or as_name in self._type_annotation_names
)
if isinstance(stmt, nodes.Import) or (
isinstance(stmt, nodes.ImportFrom) and not stmt.modname
):
if isinstance(stmt, nodes.ImportFrom) and SPECIAL_OBJ.search(
imported_name
):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if as_name == "_":
continue
if as_name is None:
msg = f"import {imported_name}"
else:
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, nodes.ImportFrom) and stmt.modname != FUTURE:
if SPECIAL_OBJ.search(imported_name):
# Filter special objects (__doc__, __all__) etc.,
# because they can be imported for exporting.
continue
if _is_from_future_import(stmt, name):
# Check if the name is in fact loaded from a
# __future__ import in another module.
continue
if is_type_annotation_import:
# Most likely a typing import if it wasn't used so far.
continue
if imported_name == "*":
unused_wildcard_imports[(stmt.modname, stmt)].append(name)
else:
if as_name is None:
msg = f"{imported_name} imported from {stmt.modname}"
else:
msg = f"{imported_name} imported from {stmt.modname} as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
# Construct string for unused-wildcard-import message
for module, unused_list in unused_wildcard_imports.items():
if len(unused_list) == 1:
arg_string = unused_list[0]
else:
arg_string = (
f"{', '.join(i for i in unused_list[:-1])} and {unused_list[-1]}"
)
self.add_message(
"unused-wildcard-import", args=(arg_string, module[0]), node=module[1]
)
del self._to_consume
def _check_metaclasses(self, node):
"""Update consumption analysis for metaclasses."""
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, nodes.ClassDef):
consumed.extend(self._check_classdef_metaclasses(child_node, node))
# Pop the consumed items, in order to avoid having
# unused-import and unused-variable false positives
for scope_locals, name in consumed:
scope_locals.pop(name, None)
def _check_classdef_metaclasses(self, klass, parent_node):
if not klass._metaclass:
# Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
return []
consumed = [] # [(scope_locals, consumed_key)]
metaclass = klass.metaclass()
name = None
if isinstance(klass._metaclass, nodes.Name):
name = klass._metaclass.name
elif isinstance(klass._metaclass, nodes.Attribute) and klass._metaclass.expr:
attr = klass._metaclass.expr
while not isinstance(attr, nodes.Name):
attr = attr.expr
name = attr.name
elif metaclass:
name = metaclass.root().name
found = _False
name = METACLASS_NAME_TRANSFORMS.get(name, name)
if name:
# check enclosing scopes starting from most local
for scope_locals, _, _, _ in self._to_consume[::-1]:
found_nodes = scope_locals.get(name, [])
for found_node in found_nodes:
if found_node.lineno <= klass.lineno:
consumed.append((scope_locals, name))
found = _True
break
# Check parent scope
nodes_in_parent_scope = parent_node.locals.get(name, [])
for found_node_parent in nodes_in_parent_scope:
if found_node_parent.lineno <= klass.lineno:
found = _True
break
if (
not found
and not metaclass
and not (
name in nodes.Module.scope_attrs
or utils.is_builtin(name)
or name in self.config.additional_builtins
)
):
self.add_message("undefined-variable", node=klass, args=(name,))
return consumed
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,701 | _fix_dot_imports | ref | function | local_names = _fix_dot_imports(not_consumed)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,742 | _is_type_checking_import | ref | function | if not _is_type_checking_import(stmt):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,743 | add_message | ref | function | self.add_message("unused-import", args=msg, node=stmt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,750 | _is_from_future_import | ref | function | if _is_from_future_import(stmt, name):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,766 | _is_type_checking_import | ref | function | if not _is_type_checking_import(stmt):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,767 | add_message | ref | function | self.add_message("unused-import", args=msg, node=stmt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,777 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,782 | _check_metaclasses | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,786 | get_children | ref | function | for child_node in node.get_children():
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,788 | _check_classdef_metaclasses | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,795 | _check_classdef_metaclasses | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,801 | metaclass | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,811 | root | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,835 | is_builtin | ref | function | or utils.is_builtin(name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,839 | add_message | ref | function | self.add_message("undefined-variable", node=klass, args=(name,))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,844 | register | def | function | def register(linter: "PyLinter") -> None:
linter.register_checker(VariablesChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,845 | register_checker | ref | function | linter.register_checker(VariablesChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/variables.py | pylint/checkers/variables.py | 2,845 | VariablesChecker | ref | function | linter.register_checker(VariablesChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/config/__init__.py | pylint/config/__init__.py | 66 | expanduser | ref | function | USER_HOME = os.path.expanduser("~")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/config/__init__.py | pylint/config/__init__.py | 70 | dirname | ref | function | USER_HOME = os.path.dirname(PYLINT_HOME)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.