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/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,203 | as_string | ref | function | values.append(comparable.as_string())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,220 | add_message | ref | function | self.add_message("consider-using-in", node=node, args=(suggestion,))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,222 | _check_chained_comparison | def | function | def _check_chained_comparison(self, node):
"""Check if there is any chained comparison in the expression.
Add a refactoring message if a boolOp contains comparison like a < b and b < c,
which can be chained as a < b < c.
Care is taken to avoid simplifying a < b < c and b < d.
"""
if node.op != "and" or len(node.values) < 2:
return
def _find_lower_upper_bounds(comparison_node, uses):
left_operand = comparison_node.left
for operator, right_operand in comparison_node.ops:
for operand in (left_operand, right_operand):
value = None
if isinstance(operand, nodes.Name):
value = operand.name
elif isinstance(operand, nodes.Const):
value = operand.value
if value is None:
continue
if operator in {"<", "<="}:
if operand is left_operand:
uses[value]["lower_bound"].add(comparison_node)
elif operand is right_operand:
uses[value]["upper_bound"].add(comparison_node)
elif operator in {">", ">="}:
if operand is left_operand:
uses[value]["upper_bound"].add(comparison_node)
elif operand is right_operand:
uses[value]["lower_bound"].add(comparison_node)
left_operand = right_operand
uses = collections.defaultdict(
lambda: {"lower_bound": set(), "upper_bound": set()}
)
for comparison_node in node.values:
if isinstance(comparison_node, nodes.Compare):
_find_lower_upper_bounds(comparison_node, uses)
for _, bounds in uses.items():
num_shared = len(bounds["lower_bound"].intersection(bounds["upper_bound"]))
num_lower_bounds = len(bounds["lower_bound"])
num_upper_bounds = len(bounds["upper_bound"])
if num_shared < num_lower_bounds and num_shared < num_upper_bounds:
self.add_message("chained-comparison", node=node)
break
@staticmethod
def _apply_boolean_simplification_rules(operator, values):
"""Removes irrelevant values or returns shortcircuiting values.
This function applies the following two rules:
1) an OR expression with _True in it will always be true, and the
reverse for AND
2) _False values in OR expressions are only relevant if all values are
false, and the reverse for AND
"""
simplified_values = []
for subnode in values:
inferred_bool = None
if not next(subnode.nodes_of_class(nodes.Name), _False):
inferred = utils.safe_infer(subnode)
if inferred:
inferred_bool = inferred.bool_value()
if not isinstance(inferred_bool, bool):
simplified_values.append(subnode)
elif (operator == "or") == inferred_bool:
return [subnode]
return simplified_values or [nodes.Const(operator == "and")]
def _simplify_boolean_operation(self, bool_op):
"""Attempts to simplify a boolean operation.
Recursively applies simplification on the operator terms,
and keeps track of whether reductions have been made.
"""
children = list(bool_op.get_children())
intermediate = [
self._simplify_boolean_operation(child)
if isinstance(child, nodes.BoolOp)
else child
for child in children
]
result = self._apply_boolean_simplification_rules(bool_op.op, intermediate)
if len(result) < len(children):
self._can_simplify_bool_op = _True
if len(result) == 1:
return result[0]
simplified_bool_op = copy.copy(bool_op)
simplified_bool_op.postinit(result)
return simplified_bool_op
def _check_simplifiable_condition(self, node):
"""Check if a boolean condition can be simplified.
Variables will not be simplified, even in the value can be inferred,
and expressions like '3 + 4' will remain expanded.
"""
if not utils.is_test_condition(node):
return
self._can_simplify_bool_op = _False
simplified_expr = self._simplify_boolean_operation(node)
if not self._can_simplify_bool_op:
return
if not next(simplified_expr.nodes_of_class(nodes.Name), _False):
self.add_message(
"condition-evals-to-constant",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
else:
self.add_message(
"simplifiable-condition",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
@utils.check_messages(
"consider-merging-isinstance",
"consider-using-in",
"chained-comparison",
"simplifiable-condition",
"condition-evals-to-constant",
)
def visit_boolop(self, node: nodes.BoolOp) -> None:
self._check_consider_merging_isinstance(node)
self._check_consider_using_in(node)
self._check_chained_comparison(node)
self._check_simplifiable_condition(node)
@staticmethod
def _is_simple_assignment(node):
return (
isinstance(node, nodes.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], nodes.AssignName)
and isinstance(node.value, nodes.Name)
)
def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,233 | _find_lower_upper_bounds | def | function | def _find_lower_upper_bounds(comparison_node, uses):
left_operand = comparison_node.left
for operator, right_operand in comparison_node.ops:
for operand in (left_operand, right_operand):
value = None
if isinstance(operand, nodes.Name):
value = operand.name
elif isinstance(operand, nodes.Const):
value = operand.value
if value is None:
continue
if operator in {"<", "<="}:
if operand is left_operand:
uses[value]["lower_bound"].add(comparison_node)
elif operand is right_operand:
uses[value]["upper_bound"].add(comparison_node)
elif operator in {">", ">="}:
if operand is left_operand:
uses[value]["upper_bound"].add(comparison_node)
elif operand is right_operand:
uses[value]["lower_bound"].add(comparison_node)
left_operand = right_operand
uses = collections.defaultdict(
lambda: {"lower_bound": set(), "upper_bound": set()}
)
for comparison_node in node.values:
if isinstance(comparison_node, nodes.Compare):
_find_lower_upper_bounds(comparison_node, uses)
for _, bounds in uses.items():
num_shared = len(bounds["lower_bound"].intersection(bounds["upper_bound"]))
num_lower_bounds = len(bounds["lower_bound"])
num_upper_bounds = len(bounds["upper_bound"])
if num_shared < num_lower_bounds and num_shared < num_upper_bounds:
self.add_message("chained-comparison", node=node)
break
@staticmethod
def _apply_boolean_simplification_rules(operator, values):
"""Removes irrelevant values or returns shortcircuiting values.
This function applies the following two rules:
1) an OR expression with _True in it will always be true, and the
reverse for AND
2) _False values in OR expressions are only relevant if all values are
false, and the reverse for AND
"""
simplified_values = []
for subnode in values:
inferred_bool = None
if not next(subnode.nodes_of_class(nodes.Name), _False):
inferred = utils.safe_infer(subnode)
if inferred:
inferred_bool = inferred.bool_value()
if not isinstance(inferred_bool, bool):
simplified_values.append(subnode)
elif (operator == "or") == inferred_bool:
return [subnode]
return simplified_values or [nodes.Const(operator == "and")]
def _simplify_boolean_operation(self, bool_op):
"""Attempts to simplify a boolean operation.
Recursively applies simplification on the operator terms,
and keeps track of whether reductions have been made.
"""
children = list(bool_op.get_children())
intermediate = [
self._simplify_boolean_operation(child)
if isinstance(child, nodes.BoolOp)
else child
for child in children
]
result = self._apply_boolean_simplification_rules(bool_op.op, intermediate)
if len(result) < len(children):
self._can_simplify_bool_op = _True
if len(result) == 1:
return result[0]
simplified_bool_op = copy.copy(bool_op)
simplified_bool_op.postinit(result)
return simplified_bool_op
def _check_simplifiable_condition(self, node):
"""Check if a boolean condition can be simplified.
Variables will not be simplified, even in the value can be inferred,
and expressions like '3 + 4' will remain expanded.
"""
if not utils.is_test_condition(node):
return
self._can_simplify_bool_op = _False
simplified_expr = self._simplify_boolean_operation(node)
if not self._can_simplify_bool_op:
return
if not next(simplified_expr.nodes_of_class(nodes.Name), _False):
self.add_message(
"condition-evals-to-constant",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
else:
self.add_message(
"simplifiable-condition",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
@utils.check_messages(
"consider-merging-isinstance",
"consider-using-in",
"chained-comparison",
"simplifiable-condition",
"condition-evals-to-constant",
)
def visit_boolop(self, node: nodes.BoolOp) -> None:
self._check_consider_merging_isinstance(node)
self._check_consider_using_in(node)
self._check_chained_comparison(node)
self._check_simplifiable_condition(node)
@staticmethod
def _is_simple_assignment(node):
return (
isinstance(node, nodes.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], nodes.AssignName)
and isinstance(node.value, nodes.Name)
)
def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,263 | _find_lower_upper_bounds | ref | function | _find_lower_upper_bounds(comparison_node, uses)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,270 | add_message | ref | function | self.add_message("chained-comparison", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,274 | _apply_boolean_simplification_rules | def | function | def _apply_boolean_simplification_rules(operator, values):
"""Removes irrelevant values or returns shortcircuiting values.
This function applies the following two rules:
1) an OR expression with _True in it will always be true, and the
reverse for AND
2) _False values in OR expressions are only relevant if all values are
false, and the reverse for AND
"""
simplified_values = []
for subnode in values:
inferred_bool = None
if not next(subnode.nodes_of_class(nodes.Name), _False):
inferred = utils.safe_infer(subnode)
if inferred:
inferred_bool = inferred.bool_value()
if not isinstance(inferred_bool, bool):
simplified_values.append(subnode)
elif (operator == "or") == inferred_bool:
return [subnode]
return simplified_values or [nodes.Const(operator == "and")]
def _simplify_boolean_operation(self, bool_op):
"""Attempts to simplify a boolean operation.
Recursively applies simplification on the operator terms,
and keeps track of whether reductions have been made.
"""
children = list(bool_op.get_children())
intermediate = [
self._simplify_boolean_operation(child)
if isinstance(child, nodes.BoolOp)
else child
for child in children
]
result = self._apply_boolean_simplification_rules(bool_op.op, intermediate)
if len(result) < len(children):
self._can_simplify_bool_op = _True
if len(result) == 1:
return result[0]
simplified_bool_op = copy.copy(bool_op)
simplified_bool_op.postinit(result)
return simplified_bool_op
def _check_simplifiable_condition(self, node):
"""Check if a boolean condition can be simplified.
Variables will not be simplified, even in the value can be inferred,
and expressions like '3 + 4' will remain expanded.
"""
if not utils.is_test_condition(node):
return
self._can_simplify_bool_op = _False
simplified_expr = self._simplify_boolean_operation(node)
if not self._can_simplify_bool_op:
return
if not next(simplified_expr.nodes_of_class(nodes.Name), _False):
self.add_message(
"condition-evals-to-constant",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
else:
self.add_message(
"simplifiable-condition",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
@utils.check_messages(
"consider-merging-isinstance",
"consider-using-in",
"chained-comparison",
"simplifiable-condition",
"condition-evals-to-constant",
)
def visit_boolop(self, node: nodes.BoolOp) -> None:
self._check_consider_merging_isinstance(node)
self._check_consider_using_in(node)
self._check_chained_comparison(node)
self._check_simplifiable_condition(node)
@staticmethod
def _is_simple_assignment(node):
return (
isinstance(node, nodes.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], nodes.AssignName)
and isinstance(node.value, nodes.Name)
)
def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,288 | nodes_of_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,289 | safe_infer | ref | function | inferred = utils.safe_infer(subnode)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,291 | bool_value | ref | function | inferred_bool = inferred.bool_value()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,298 | Const | ref | function | return simplified_values or [nodes.Const(operator == "and")]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,300 | _simplify_boolean_operation | def | function | def _simplify_boolean_operation(self, bool_op):
"""Attempts to simplify a boolean operation.
Recursively applies simplification on the operator terms,
and keeps track of whether reductions have been made.
"""
children = list(bool_op.get_children())
intermediate = [
self._simplify_boolean_operation(child)
if isinstance(child, nodes.BoolOp)
else child
for child in children
]
result = self._apply_boolean_simplification_rules(bool_op.op, intermediate)
if len(result) < len(children):
self._can_simplify_bool_op = _True
if len(result) == 1:
return result[0]
simplified_bool_op = copy.copy(bool_op)
simplified_bool_op.postinit(result)
return simplified_bool_op
def _check_simplifiable_condition(self, node):
"""Check if a boolean condition can be simplified.
Variables will not be simplified, even in the value can be inferred,
and expressions like '3 + 4' will remain expanded.
"""
if not utils.is_test_condition(node):
return
self._can_simplify_bool_op = _False
simplified_expr = self._simplify_boolean_operation(node)
if not self._can_simplify_bool_op:
return
if not next(simplified_expr.nodes_of_class(nodes.Name), _False):
self.add_message(
"condition-evals-to-constant",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
else:
self.add_message(
"simplifiable-condition",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
@utils.check_messages(
"consider-merging-isinstance",
"consider-using-in",
"chained-comparison",
"simplifiable-condition",
"condition-evals-to-constant",
)
def visit_boolop(self, node: nodes.BoolOp) -> None:
self._check_consider_merging_isinstance(node)
self._check_consider_using_in(node)
self._check_chained_comparison(node)
self._check_simplifiable_condition(node)
@staticmethod
def _is_simple_assignment(node):
return (
isinstance(node, nodes.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], nodes.AssignName)
and isinstance(node.value, nodes.Name)
)
def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,306 | get_children | ref | function | children = list(bool_op.get_children())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,308 | _simplify_boolean_operation | ref | function | self._simplify_boolean_operation(child)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,313 | _apply_boolean_simplification_rules | ref | function | result = self._apply_boolean_simplification_rules(bool_op.op, intermediate)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,319 | postinit | ref | function | simplified_bool_op.postinit(result)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,322 | _check_simplifiable_condition | def | function | def _check_simplifiable_condition(self, node):
"""Check if a boolean condition can be simplified.
Variables will not be simplified, even in the value can be inferred,
and expressions like '3 + 4' will remain expanded.
"""
if not utils.is_test_condition(node):
return
self._can_simplify_bool_op = _False
simplified_expr = self._simplify_boolean_operation(node)
if not self._can_simplify_bool_op:
return
if not next(simplified_expr.nodes_of_class(nodes.Name), _False):
self.add_message(
"condition-evals-to-constant",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
else:
self.add_message(
"simplifiable-condition",
node=node,
args=(node.as_string(), simplified_expr.as_string()),
)
@utils.check_messages(
"consider-merging-isinstance",
"consider-using-in",
"chained-comparison",
"simplifiable-condition",
"condition-evals-to-constant",
)
def visit_boolop(self, node: nodes.BoolOp) -> None:
self._check_consider_merging_isinstance(node)
self._check_consider_using_in(node)
self._check_chained_comparison(node)
self._check_simplifiable_condition(node)
@staticmethod
def _is_simple_assignment(node):
return (
isinstance(node, nodes.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], nodes.AssignName)
and isinstance(node.value, nodes.Name)
)
def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,328 | is_test_condition | ref | function | if not utils.is_test_condition(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,332 | _simplify_boolean_operation | ref | function | simplified_expr = self._simplify_boolean_operation(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,337 | nodes_of_class | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,338 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,341 | as_string | ref | function | args=(node.as_string(), simplified_expr.as_string()),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,341 | as_string | ref | function | args=(node.as_string(), simplified_expr.as_string()),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,344 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,347 | as_string | ref | function | args=(node.as_string(), simplified_expr.as_string()),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,347 | as_string | ref | function | args=(node.as_string(), simplified_expr.as_string()),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,350 | check_messages | ref | function | @utils.check_messages(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,357 | visit_boolop | def | function | def visit_boolop(self, node: nodes.BoolOp) -> None:
self._check_consider_merging_isinstance(node)
self._check_consider_using_in(node)
self._check_chained_comparison(node)
self._check_simplifiable_condition(node)
@staticmethod
def _is_simple_assignment(node):
return (
isinstance(node, nodes.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], nodes.AssignName)
and isinstance(node.value, nodes.Name)
)
def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,358 | _check_consider_merging_isinstance | ref | function | self._check_consider_merging_isinstance(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,359 | _check_consider_using_in | ref | function | self._check_consider_using_in(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,360 | _check_chained_comparison | ref | function | self._check_chained_comparison(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,361 | _check_simplifiable_condition | ref | function | self._check_simplifiable_condition(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,364 | _is_simple_assignment | def | function | def _is_simple_assignment(node):
return (
isinstance(node, nodes.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], nodes.AssignName)
and isinstance(node.value, nodes.Name)
)
def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,372 | _check_swap_variables | def | function | def _check_swap_variables(self, node):
if not node.next_sibling() or not node.next_sibling().next_sibling():
return
assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
if not all(self._is_simple_assignment(node) for node in assignments):
return
if any(node in self._reported_swap_nodes for node in assignments):
return
left = [node.targets[0].name for node in assignments]
right = [node.value.name for node in assignments]
if left[0] == right[-1] and left[1:] == right[:-1]:
self._reported_swap_nodes.update(assignments)
message = "consider-swap-variables"
self.add_message(message, node=node)
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
"consider-using-with",
)
def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,373 | next_sibling | ref | function | if not node.next_sibling() or not node.next_sibling().next_sibling():
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,373 | next_sibling | ref | function | if not node.next_sibling() or not node.next_sibling().next_sibling():
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,373 | next_sibling | ref | function | if not node.next_sibling() or not node.next_sibling().next_sibling():
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,375 | next_sibling | ref | function | assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,375 | next_sibling | ref | function | assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,375 | next_sibling | ref | function | assignments = [node, node.next_sibling(), node.next_sibling().next_sibling()]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,376 | _is_simple_assignment | ref | function | if not all(self._is_simple_assignment(node) for node in assignments):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,385 | add_message | ref | function | self.add_message(message, node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,387 | check_messages | ref | function | @utils.check_messages(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,393 | visit_assign | def | function | def visit_assign(self, node: nodes.Assign) -> None:
self._append_context_managers_to_stack(node)
self.visit_return(node) # remaining checks are identical as for return nodes
@utils.check_messages(
"simplify-boolean-expression",
"consider-using-ternary",
"consider-swap-variables",
)
def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,394 | _append_context_managers_to_stack | ref | function | self._append_context_managers_to_stack(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,395 | visit_return | ref | function | self.visit_return(node) # remaining checks are identical as for return nodes
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,397 | check_messages | ref | function | @utils.check_messages(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,402 | visit_return | def | function | def visit_return(self, node: nodes.Return) -> None:
self._check_swap_variables(node)
if self._is_and_or_ternary(node.value):
cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
else:
return
if all(
isinstance(value, nodes.Compare) for value in (truth_value, false_value)
):
return
inferred_truth_value = utils.safe_infer(truth_value)
if inferred_truth_value is None or inferred_truth_value == astroid.Uninferable:
truth_boolean_value = _True
else:
truth_boolean_value = inferred_truth_value.bool_value()
if truth_boolean_value is _False:
message = "simplify-boolean-expression"
suggestion = false_value.as_string()
else:
message = "consider-using-ternary"
suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
self.add_message(message, node=node, args=(suggestion,))
def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,403 | _check_swap_variables | ref | function | self._check_swap_variables(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,404 | _is_and_or_ternary | ref | function | if self._is_and_or_ternary(node.value):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,405 | _and_or_ternary_arguments | ref | function | cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,414 | safe_infer | ref | function | inferred_truth_value = utils.safe_infer(truth_value)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,418 | bool_value | ref | function | truth_boolean_value = inferred_truth_value.bool_value()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,422 | as_string | ref | function | suggestion = false_value.as_string()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,425 | as_string | ref | function | suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,425 | as_string | ref | function | suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,425 | as_string | ref | function | suggestion = f"{truth_value.as_string()} if {cond.as_string()} else {false_value.as_string()}"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,426 | add_message | ref | function | self.add_message(message, node=node, args=(suggestion,))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,428 | _append_context_managers_to_stack | def | function | def _append_context_managers_to_stack(self, node: nodes.Assign) -> None:
if _is_inside_context_manager(node):
# if we are inside a context manager itself, we assume that it will handle the resource management itself.
return
if isinstance(node.targets[0], (nodes.Tuple, nodes.List, nodes.Set)):
assignees = node.targets[0].elts
value = utils.safe_infer(node.value)
if value is None or not hasattr(value, "elts"):
# We cannot deduce what values are assigned, so we have to skip this
return
values = value.elts
else:
assignees = [node.targets[0]]
values = [node.value]
if Uninferable in (assignees, values):
return
for assignee, value in zip(assignees, values):
if not isinstance(value, nodes.Call):
continue
inferred = utils.safe_infer(value.func)
if (
not inferred
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
or not isinstance(assignee, (nodes.AssignName, nodes.AssignAttr))
):
continue
stack = self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
)
varname = (
assignee.name
if isinstance(assignee, nodes.AssignName)
else assignee.attrname
)
if varname in stack:
existing_node = stack[varname]
if astroid.are_exclusive(node, existing_node):
# only one of the two assignments can be executed at runtime, thus it is fine
stack[varname] = value
continue
# variable was redefined before it was used in a ``with`` block
self.add_message(
"consider-using-with",
node=existing_node,
)
stack[varname] = value
def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,429 | _is_inside_context_manager | ref | function | if _is_inside_context_manager(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,434 | safe_infer | ref | function | value = utils.safe_infer(node.value)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,447 | safe_infer | ref | function | inferred = utils.safe_infer(value.func)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,450 | qname | ref | function | or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,454 | get_stack_for_frame | ref | function | stack = self._consider_using_with_stack.get_stack_for_frame(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,455 | frame | ref | function | node.frame(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,464 | are_exclusive | ref | function | if astroid.are_exclusive(node, existing_node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,469 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,475 | _check_consider_using_with | def | function | def _check_consider_using_with(self, node: nodes.Call):
if _is_inside_context_manager(node) or _is_a_return_statement(node):
# If we are inside a context manager itself, we assume that it will handle the resource management itself.
# If the node is a child of a return, we assume that the caller knows he is getting a context manager
# he should use properly (i.e. in a ``with``).
return
if (
node
in self._consider_using_with_stack.get_stack_for_frame(
node.frame(future=_True)
).values()
):
# the result of this call was already assigned to a variable and will be checked when leaving the scope.
return
inferred = utils.safe_infer(node.func)
if not inferred:
return
could_be_used_in_with = (
# things like ``lock.acquire()``
inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
or (
# things like ``open("foo")`` which are not already inside a ``with`` statement
inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
and not _is_part_of_with_items(node)
)
)
if could_be_used_in_with and not _will_be_released_automatically(node):
self.add_message("consider-using-with", node=node)
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,476 | _is_inside_context_manager | ref | function | if _is_inside_context_manager(node) or _is_a_return_statement(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,476 | _is_a_return_statement | ref | function | if _is_inside_context_manager(node) or _is_a_return_statement(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,483 | get_stack_for_frame | ref | function | in self._consider_using_with_stack.get_stack_for_frame(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,484 | frame | ref | function | node.frame(future=True)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,489 | safe_infer | ref | function | inferred = utils.safe_infer(node.func)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,494 | qname | ref | function | inferred.qname() in CALLS_THAT_COULD_BE_REPLACED_BY_WITH
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,497 | qname | ref | function | inferred.qname() in CALLS_RETURNING_CONTEXT_MANAGERS
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,498 | _is_part_of_with_items | ref | function | and not _is_part_of_with_items(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,501 | _will_be_released_automatically | ref | function | if could_be_used_in_with and not _will_be_released_automatically(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,502 | add_message | ref | function | self.add_message("consider-using-with", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,504 | _check_use_list_or_dict_literal | def | function | def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
"""Check if empty list or dict is created by using the literal [] or {}."""
if node.as_string() in {"list()", "dict()"}:
inferred = utils.safe_infer(node.func)
if isinstance(inferred, nodes.ClassDef) and not node.args:
if inferred.qname() == "builtins.list":
self.add_message("use-list-literal", node=node)
elif inferred.qname() == "builtins.dict" and not node.keywords:
self.add_message("use-dict-literal", node=node)
def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,506 | as_string | ref | function | if node.as_string() in {"list()", "dict()"}:
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,507 | safe_infer | ref | function | inferred = utils.safe_infer(node.func)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,509 | qname | ref | function | if inferred.qname() == "builtins.list":
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,510 | add_message | ref | function | self.add_message("use-list-literal", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,511 | qname | ref | function | elif inferred.qname() == "builtins.dict" and not node.keywords:
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,512 | add_message | ref | function | self.add_message("use-dict-literal", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,514 | _check_consider_using_join | def | function | def _check_consider_using_join(self, aug_assign):
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
"""
for_loop = aug_assign.parent
if not isinstance(for_loop, nodes.For) or len(for_loop.body) > 1:
return
assign = for_loop.previous_sibling()
if not isinstance(assign, nodes.Assign):
return
result_assign_names = {
target.name
for target in assign.targets
if isinstance(target, nodes.AssignName)
}
is_concat_loop = (
aug_assign.op == "+="
and isinstance(aug_assign.target, nodes.AssignName)
and len(for_loop.body) == 1
and aug_assign.target.name in result_assign_names
and isinstance(assign.value, nodes.Const)
and isinstance(assign.value.value, str)
and isinstance(aug_assign.value, nodes.Name)
and aug_assign.value.name == for_loop.target.name
)
if is_concat_loop:
self.add_message("consider-using-join", node=aug_assign)
@utils.check_messages("consider-using-join")
def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,524 | previous_sibling | ref | function | assign = for_loop.previous_sibling()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,544 | add_message | ref | function | self.add_message("consider-using-join", node=aug_assign)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,546 | check_messages | ref | function | @utils.check_messages("consider-using-join")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,547 | visit_augassign | def | function | def visit_augassign(self, node: nodes.AugAssign) -> None:
self._check_consider_using_join(node)
@utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,548 | _check_consider_using_join | ref | function | self._check_consider_using_join(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,550 | check_messages | ref | function | @utils.check_messages("unnecessary-comprehension", "unnecessary-dict-index-lookup")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,551 | visit_comprehension | def | function | def visit_comprehension(self, node: nodes.Comprehension) -> None:
self._check_unnecessary_comprehension(node)
self._check_unnecessary_dict_index_lookup(node)
def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,552 | _check_unnecessary_comprehension | ref | function | self._check_unnecessary_comprehension(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,553 | _check_unnecessary_dict_index_lookup | ref | function | self._check_unnecessary_dict_index_lookup(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,555 | _check_unnecessary_comprehension | def | function | def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:
if (
isinstance(node.parent, nodes.GeneratorExp)
or len(node.ifs) != 0
or len(node.parent.generators) != 1
or node.is_async
):
return
if (
isinstance(node.parent, nodes.DictComp)
and isinstance(node.parent.key, nodes.Name)
and isinstance(node.parent.value, nodes.Name)
and isinstance(node.target, nodes.Tuple)
and all(isinstance(elt, nodes.AssignName) for elt in node.target.elts)
):
expr_list = [node.parent.key.name, node.parent.value.name]
target_list = [elt.name for elt in node.target.elts]
elif isinstance(node.parent, (nodes.ListComp, nodes.SetComp)):
expr = node.parent.elt
if isinstance(expr, nodes.Name):
expr_list = expr.name
elif isinstance(expr, nodes.Tuple):
if any(not isinstance(elt, nodes.Name) for elt in expr.elts):
return
expr_list = [elt.name for elt in expr.elts]
else:
expr_list = []
target = node.parent.generators[0].target
target_list = (
target.name
if isinstance(target, nodes.AssignName)
else (
[
elt.name
for elt in target.elts
if isinstance(elt, nodes.AssignName)
]
if isinstance(target, nodes.Tuple)
else []
)
)
else:
return
if expr_list == target_list and expr_list:
args: Optional[Tuple[str]] = None
inferred = utils.safe_infer(node.iter)
if isinstance(node.parent, nodes.DictComp) and isinstance(
inferred, astroid.objects.DictItems
):
args = (f"{node.iter.func.expr.as_string()}",)
elif (
isinstance(node.parent, nodes.ListComp)
and isinstance(inferred, nodes.List)
) or (
isinstance(node.parent, nodes.SetComp)
and isinstance(inferred, nodes.Set)
):
args = (f"{node.iter.as_string()}",)
if args:
self.add_message(
"unnecessary-comprehension", node=node.parent, args=args
)
return
if isinstance(node.parent, nodes.DictComp):
func = "dict"
elif isinstance(node.parent, nodes.ListComp):
func = "list"
elif isinstance(node.parent, nodes.SetComp):
func = "set"
else:
return
self.add_message(
"unnecessary-comprehension",
node=node.parent,
args=(f"{func}({node.iter.as_string()})",),
)
@staticmethod
def _is_and_or_ternary(node):
"""Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, nodes.BoolOp)
and node.op == "or"
and len(node.values) == 2
and isinstance(node.values[0], nodes.BoolOp)
and not isinstance(node.values[1], nodes.BoolOp)
and node.values[0].op == "and"
and not isinstance(node.values[0].values[1], nodes.BoolOp)
and len(node.values[0].values) == 2
)
@staticmethod
def _and_or_ternary_arguments(node):
false_value = node.values[1]
condition, true_value = node.values[0].values
return condition, true_value, false_value
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._return_nodes[node.name] = list(
node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
def _check_consistent_returns(self, node: nodes.FunctionDef) -> None:
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit return.
Args:
node (nodes.FunctionDef): the function holding the return statements.
"""
# explicit return statements are those with a not None value
explicit_returns = [
_node for _node in self._return_nodes[node.name] if _node.value is not None
]
if not explicit_returns:
return
if len(explicit_returns) == len(
self._return_nodes[node.name]
) and self._is_node_return_ended(node):
return
self.add_message("inconsistent-return-statements", node=node)
def _is_if_node_return_ended(self, node: nodes.If) -> bool:
"""Check if the If node ends with an explicit return statement.
Args:
node (nodes.If): If node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Do not check if inner function definition are return ended.
is_if_returning = any(
self._is_node_return_ended(_ifn)
for _ifn in node.body
if not isinstance(_ifn, nodes.FunctionDef)
)
if not node.orelse:
# If there is not orelse part then the if statement is returning if :
# - there is at least one return statement in its siblings;
# - the if body is itself returning.
if not self._has_return_in_siblings(node):
return _False
return is_if_returning
# If there is an orelse part then both if body and orelse part should return.
is_orelse_returning = any(
self._is_node_return_ended(_ore)
for _ore in node.orelse
if not isinstance(_ore, nodes.FunctionDef)
)
return is_if_returning and is_orelse_returning
def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool:
"""Check if the Raise node ends with an explicit return statement.
Args:
node (nodes.Raise): Raise node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# a Raise statement doesn't need to end with a return statement
# but if the exception raised is handled, then the handler has to
# ends with a return statement
if not node.exc:
# Ignore bare raises
return _True
if not utils.is_node_inside_try_except(node):
# If the raise statement is not inside a try/except statement
# then the exception is raised and cannot be caught. No need
# to infer it.
return _True
exc = utils.safe_infer(node.exc)
if exc is None or exc is astroid.Uninferable or not hasattr(exc, "pytype"):
return _False
exc_name = exc.pytype().split(".")[-1]
handlers = utils.get_exception_handlers(node, exc_name)
handlers = list(handlers) if handlers is not None else []
if handlers:
# among all the handlers handling the exception at least one
# must end with a return statement
return any(self._is_node_return_ended(_handler) for _handler in handlers)
# if no handlers handle the exception then it's ok
return _True
def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
"""Check if the node ends with an explicit return statement.
Args:
node (nodes.NodeNG): node to be checked.
Returns:
bool: _True if the node ends with an explicit statement, _False otherwise.
"""
# Recursion base case
if isinstance(node, nodes.Return):
return _True
if isinstance(node, nodes.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
return _True
except astroid.InferenceError:
pass
# Avoid the check inside while loop as we don't know
# if they will be completed
if isinstance(node, nodes.While):
return _True
if isinstance(node, nodes.Raise):
return self._is_raise_node_return_ended(node)
if isinstance(node, nodes.If):
return self._is_if_node_return_ended(node)
if isinstance(node, nodes.TryExcept):
handlers = {
_child
for _child in node.get_children()
if isinstance(_child, nodes.ExceptHandler)
}
all_but_handler = set(node.get_children()) - handlers
return any(
self._is_node_return_ended(_child) for _child in all_but_handler
) and all(self._is_node_return_ended(_child) for _child in handlers)
if (
isinstance(node, nodes.Assert)
and isinstance(node.test, nodes.Const)
and not node.test.value
):
# consider assert _False as a return node
return _True
# recurses on the children of the node
return any(self._is_node_return_ended(_child) for _child in node.get_children())
@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""Returns _True if there is at least one return in the node's siblings."""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
return _True
next_sibling = next_sibling.next_sibling()
return _False
def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool:
"""Return _True if the function never returns. _False otherwise.
Args:
node (nodes.FunctionDef): function definition node to be analyzed.
Returns:
bool: _True if the function never returns, _False otherwise.
"""
if isinstance(node, nodes.FunctionDef) and node.returns:
return (
isinstance(node.returns, nodes.Attribute)
and node.returns.attrname == "NoReturn"
or isinstance(node.returns, nodes.Name)
and node.returns.name == "NoReturn"
)
try:
return node.qname() in self._never_returning_functions
except TypeError:
return _False
def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement
in the function body. Otherwise _check_consistent_returns() is called!
Per its implementation and PEP8 we can have a "return None" at the end
of the function body if there are other return statements before that!
"""
if len(self._return_nodes[node.name]) > 1:
return
if len(node.body) <= 1:
return
last = node.body[-1]
if isinstance(last, nodes.Return):
# e.g. "return"
if last.value is None:
self.add_message("useless-return", node=node)
# return None"
elif isinstance(last.value, nodes.Const) and (last.value.value is None):
self.add_message("useless-return", node=node)
def _check_unnecessary_dict_index_lookup(
self, node: Union[nodes.For, nodes.Comprehension]
) -> None:
"""Add message when accessing dict values by index lookup."""
# Verify that we have an .items() call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper items call?
if (
isinstance(node.iter, nodes.Call)
and isinstance(node.iter.func, nodes.Attribute)
and node.iter.func.attrname == "items"
):
inferred = utils.safe_infer(node.iter.func)
if not isinstance(inferred, astroid.BoundMethod):
return
iterating_object_name = node.iter.func.expr.as_string()
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
children = (
node.body if isinstance(node, nodes.For) else node.parent.get_children()
)
for child in children:
for subscript in child.nodes_of_class(nodes.Subscript):
if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)):
continue
value = subscript.slice
if isinstance(node, nodes.For) and (
isinstance(subscript.parent, nodes.Assign)
and subscript in subscript.parent.targets
or isinstance(subscript.parent, nodes.AugAssign)
and subscript == subscript.parent.target
):
# Ignore this subscript if it is the target of an assignment
# Early termination; after reassignment dict index lookup will be necessary
return
if isinstance(subscript.parent, nodes.Delete):
# Ignore this subscript if it's used with the delete keyword
return
# Case where .items is assigned to k,v (i.e., for k, v in d.items())
if isinstance(value, nodes.Name):
if (
not isinstance(node.target, nodes.Tuple)
# Ignore 1-tuples: for k, in d.items()
or len(node.target.elts) < 2
or value.name != node.target.elts[0].name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.lookup(value.name)[1][-1].lineno > node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=(node.target.elts[1].as_string()),
)
# Case where .items is assigned to single var (i.e., for item in d.items())
elif isinstance(value, nodes.Subscript):
if (
not isinstance(node.target, nodes.AssignName)
or node.target.name != value.value.name
or iterating_object_name != subscript.value.as_string()
):
continue
if (
isinstance(node, nodes.For)
and value.value.lookup(value.value.name)[1][-1].lineno
> node.lineno
):
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
# check if subscripted by 0 (key)
inferred = utils.safe_infer(value.slice)
if not isinstance(inferred, nodes.Const) or inferred.value != 0:
continue
self.add_message(
"unnecessary-dict-index-lookup",
node=subscript,
args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,602 | safe_infer | ref | function | inferred = utils.safe_infer(node.iter)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,606 | as_string | ref | function | args = (f"{node.iter.func.expr.as_string()}",)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,614 | as_string | ref | function | args = (f"{node.iter.as_string()}",)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,616 | add_message | ref | function | self.add_message(
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.