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,630 | 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,633 | as_string | ref | function | args=(f"{func}({node.iter.as_string()})",),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,637 | _is_and_or_ternary | def | function | 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,654 | _and_or_ternary_arguments | def | function | 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,659 | visit_functiondef | def | function | 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,661 | 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,664 | _check_consistent_returns | def | function | 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,683 | _is_node_return_ended | ref | function | ) and self._is_node_return_ended(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,685 | add_message | ref | function | self.add_message("inconsistent-return-statements", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,687 | _is_if_node_return_ended | def | function | 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,698 | _is_node_return_ended | ref | function | self._is_node_return_ended(_ifn)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,706 | _has_return_in_siblings | ref | function | if not self._has_return_in_siblings(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,711 | _is_node_return_ended | ref | function | self._is_node_return_ended(_ore)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,717 | _is_raise_node_return_ended | def | function | 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,732 | is_node_inside_try_except | ref | function | if not utils.is_node_inside_try_except(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,737 | safe_infer | ref | function | exc = utils.safe_infer(node.exc)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,740 | pytype | ref | function | exc_name = exc.pytype().split(".")[-1]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,741 | get_exception_handlers | ref | function | handlers = utils.get_exception_handlers(node, exc_name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,746 | _is_node_return_ended | ref | function | return any(self._is_node_return_ended(_handler) for _handler in handlers)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,750 | _is_node_return_ended | def | function | 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,765 | inferred | ref | function | funcdef_node = node.func.inferred()[0]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,766 | _is_function_def_never_returning | ref | function | if self._is_function_def_never_returning(funcdef_node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,775 | _is_raise_node_return_ended | ref | function | return self._is_raise_node_return_ended(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,777 | _is_if_node_return_ended | ref | function | return self._is_if_node_return_ended(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,781 | get_children | ref | function | for _child in node.get_children()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,784 | get_children | ref | function | all_but_handler = set(node.get_children()) - handlers
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,786 | _is_node_return_ended | ref | function | self._is_node_return_ended(_child) for _child in all_but_handler
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,787 | _is_node_return_ended | ref | function | ) and all(self._is_node_return_ended(_child) for _child in handlers)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,796 | _is_node_return_ended | ref | function | return any(self._is_node_return_ended(_child) for _child in node.get_children())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,796 | get_children | ref | function | return any(self._is_node_return_ended(_child) for _child in node.get_children())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,799 | _has_return_in_siblings | def | function | 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,801 | next_sibling | ref | function | next_sibling = node.next_sibling()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,805 | next_sibling | ref | function | next_sibling = next_sibling.next_sibling()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,808 | _is_function_def_never_returning | def | function | 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,825 | qname | ref | function | return node.qname() in self._never_returning_functions
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,829 | _check_return_at_the_end | def | function | 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,848 | add_message | ref | function | self.add_message("useless-return", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,851 | add_message | ref | function | self.add_message("useless-return", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,853 | _check_unnecessary_dict_index_lookup | def | function | 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,866 | safe_infer | ref | function | inferred = utils.safe_infer(node.iter.func)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,869 | as_string | ref | function | iterating_object_name = 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,877 | get_children | ref | function | node.body if isinstance(node, nodes.For) else node.parent.get_children()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,880 | 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,906 | as_string | ref | function | or iterating_object_name != subscript.value.as_string()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,920 | 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,923 | as_string | ref | function | args=(node.target.elts[1].as_string()),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,931 | as_string | ref | function | or iterating_object_name != subscript.value.as_string()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,947 | safe_infer | ref | function | inferred = utils.safe_infer(value.slice)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/refactoring/refactoring_checker.py | pylint/checkers/refactoring/refactoring_checker.py | 1,950 | 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,953 | as_string | ref | function | args=("1".join(value.as_string().rsplit("0", maxsplit=1)),),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 94 | LineSpecifs | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 110 | CplSuccessiveLinesLimits | def | class | __init__ |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 134 | LinesChunk | def | class | __init__ __eq__ __hash__ __repr__ __str__ |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 143 | Index | ref | function | self._index: Index = Index(num_line)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 169 | SuccessiveLinesLimits | def | class | __init__ start end end __repr__ |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 182 | start | def | function | def start(self) -> LineNumber:
return self._start
@property
def end(self) -> LineNumber:
return self._end
@end.setter
def end(self, value: LineNumber) -> None:
self._end = value
def __repr__(self) -> str:
return f"<SuccessiveLinesLimits <{self._start};{self._end}>>"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 186 | end | def | function | def end(self) -> LineNumber:
return self._end
@end.setter
def end(self, value: LineNumber) -> None:
self._end = value
def __repr__(self) -> str:
return f"<SuccessiveLinesLimits <{self._start};{self._end}>>"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 190 | end | def | function | def end(self, value: LineNumber) -> None:
self._end = value
def __repr__(self) -> str:
return f"<SuccessiveLinesLimits <{self._start};{self._end}>>"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 197 | LineSetStartCouple | def | class | __repr__ __eq__ __hash__ increment |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 219 | increment | def | function | def increment(self, value: Index) -> "LineSetStartCouple":
return LineSetStartCouple(
Index(self.fst_lineset_index + value),
Index(self.snd_lineset_index + value),
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 220 | LineSetStartCouple | ref | function | return LineSetStartCouple(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 221 | Index | ref | function | Index(self.fst_lineset_index + value),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 222 | Index | ref | function | Index(self.snd_lineset_index + value),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 229 | hash_lineset | def | function | def hash_lineset(
lineset: "LineSet", min_common_lines: int = DEFAULT_MIN_SIMILARITY_LINE
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 259 | Index | ref | function | index = Index(index_i)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 260 | SuccessiveLinesLimits | ref | function | index2lines[index] = SuccessiveLinesLimits(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 261 | LineNumber | ref | function | start=LineNumber(start_linenumber), end=LineNumber(end_linenumber)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 261 | LineNumber | ref | function | start=LineNumber(start_linenumber), end=LineNumber(end_linenumber)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 264 | LinesChunk | ref | function | l_c = LinesChunk(lineset.name, index, *succ_lines)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 270 | remove_successives | def | function | def remove_successives(all_couples: CplIndexToCplLines_T) -> None:
"""Removes all successive entries in the dictionary in argument.
:param all_couples: collection that has to be cleaned up from successives entries.
The keys are couples of indices that mark the beginning of common entries
in both linesets. The values have two parts. The first one is the couple
of starting and ending line numbers of common successives lines in the first file.
The second part is the same for the second file.
For example consider the following dict:
>>> all_couples
{(11, 34): ([5, 9], [27, 31]),
(23, 79): ([15, 19], [45, 49]),
(12, 35): ([6, 10], [28, 32])}
There are two successives keys (11, 34) and (12, 35).
It means there are two consecutive similar chunks of lines in both files.
Thus remove last entry and update the last line numbers in the first entry
>>> remove_successives(all_couples)
>>> all_couples
{(11, 34): ([5, 10], [27, 32]),
(23, 79): ([15, 19], [45, 49])}
"""
couple: LineSetStartCouple
for couple in tuple(all_couples.keys()):
to_remove = []
test = couple.increment(Index(1))
while test in all_couples:
all_couples[couple].first_file.end = all_couples[test].first_file.end
all_couples[couple].second_file.end = all_couples[test].second_file.end
all_couples[couple].effective_cmn_lines_nb += 1
to_remove.append(test)
test = test.increment(Index(1))
for target in to_remove:
try:
all_couples.pop(target)
except KeyError:
pass
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 298 | increment | ref | function | test = couple.increment(Index(1))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 298 | Index | ref | function | test = couple.increment(Index(1))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 304 | increment | ref | function | test = test.increment(Index(1))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 304 | Index | ref | function | test = test.increment(Index(1))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 313 | filter_noncode_lines | def | function | def filter_noncode_lines(
ls_1: "LineSet",
stindex_1: Index,
ls_2: "LineSet",
stindex_2: Index,
common_lines_nb: int,
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 344 | Commonality | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 354 | Similar | def | class | __init__ append_stream run _compute_sims _display_sims _get_similarity_report _find_common _iter_sims get_map_data combine_mapreduce_data |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 372 | append_stream | def | function | def append_stream(
self, streamid: str, stream: STREAM_TYPES, encoding: Optional[str] = None
) -> None:
"""Append a file to search for similarities."""
if isinstance(stream, BufferedIOBase):
if encoding is None:
raise ValueError
readlines = decoding_stream(stream, encoding).readlines
else:
readlines = stream.readlines # type: ignore[assignment] # hint parameter is incorrectly typed as non-optional
try:
self.linesets.append(
LineSet(
streamid,
readlines(),
self.ignore_comments,
self.ignore_docstrings,
self.ignore_imports,
self.ignore_signatures,
)
)
except UnicodeDecodeError:
pass
def run(self) -> None:
"""Start looking for similarities and display results on stdout."""
if self.min_lines == 0:
return
self._display_sims(self._compute_sims())
def _compute_sims(self) -> List[Tuple[int, Set[LinesChunkLimits_T]]]:
"""Compute similarities in appended files."""
no_duplicates: Dict[int, List[Set[LinesChunkLimits_T]]] = defaultdict(list)
for commonality in self._iter_sims():
num = commonality.cmn_lines_nb
lineset1 = commonality.fst_lset
start_line_1 = commonality.fst_file_start
end_line_1 = commonality.fst_file_end
lineset2 = commonality.snd_lset
start_line_2 = commonality.snd_file_start
end_line_2 = commonality.snd_file_end
duplicate = no_duplicates[num]
couples: Set[LinesChunkLimits_T]
for couples in duplicate:
if (lineset1, start_line_1, end_line_1) in couples or (
lineset2,
start_line_2,
end_line_2,
) in couples:
break
else:
duplicate.append(
{
(lineset1, start_line_1, end_line_1),
(lineset2, start_line_2, end_line_2),
}
)
sims: List[Tuple[int, Set[LinesChunkLimits_T]]] = []
ensembles: List[Set[LinesChunkLimits_T]]
for num, ensembles in no_duplicates.items():
cpls: Set[LinesChunkLimits_T]
for cpls in ensembles:
sims.append((num, cpls))
sims.sort()
sims.reverse()
return sims
def _display_sims(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> None:
"""Display computed similarities on stdout."""
report = self._get_similarity_report(similarities)
print(report)
def _get_similarity_report(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> str:
"""Create a report from similarities."""
report: str = ""
duplicated_line_number: int = 0
for number, couples in similarities:
report += f"\n{number} similar lines in {len(couples)} files\n"
couples_l = sorted(couples)
line_set = start_line = end_line = None
for line_set, start_line, end_line in couples_l:
report += f"=={line_set.name}:[{start_line}:{end_line}]\n"
if line_set:
for line in line_set._real_lines[start_line:end_line]:
report += f" {line.rstrip()}\n" if line.rstrip() else "\n"
duplicated_line_number += number * (len(couples_l) - 1)
total_line_number: int = sum(len(lineset) for lineset in self.linesets)
report += f"TOTAL lines={total_line_number} duplicates={duplicated_line_number} percent={duplicated_line_number * 100.0 / total_line_number:.2f}\n"
return report
def _find_common(
self, lineset1: "LineSet", lineset2: "LineSet"
) -> Generator[Commonality, None, None]:
"""Find similarities in the two given linesets.
This the core of the algorithm.
The idea is to compute the hashes of a minimal number of successive lines of each lineset and then compare the hashes.
Every match of such comparison is stored in a dict that links the couple of starting indices in both linesets to
the couple of corresponding starting and ending lines in both files.
Last regroups all successive couples in a bigger one. It allows to take into account common chunk of lines that have more
than the minimal number of successive lines required.
"""
hash_to_index_1: HashToIndex_T
hash_to_index_2: HashToIndex_T
index_to_lines_1: IndexToLines_T
index_to_lines_2: IndexToLines_T
hash_to_index_1, index_to_lines_1 = hash_lineset(lineset1, self.min_lines)
hash_to_index_2, index_to_lines_2 = hash_lineset(lineset2, self.min_lines)
hash_1: FrozenSet[LinesChunk] = frozenset(hash_to_index_1.keys())
hash_2: FrozenSet[LinesChunk] = frozenset(hash_to_index_2.keys())
common_hashes: Iterable[LinesChunk] = sorted(
hash_1 & hash_2, key=lambda m: hash_to_index_1[m][0]
)
# all_couples is a dict that links the couple of indices in both linesets that mark the beginning of
# successive common lines, to the corresponding starting and ending number lines in both files
all_couples: CplIndexToCplLines_T = {}
for c_hash in sorted(common_hashes, key=operator.attrgetter("_index")):
for indices_in_linesets in itertools.product(
hash_to_index_1[c_hash], hash_to_index_2[c_hash]
):
index_1 = indices_in_linesets[0]
index_2 = indices_in_linesets[1]
all_couples[
LineSetStartCouple(index_1, index_2)
] = CplSuccessiveLinesLimits(
copy.copy(index_to_lines_1[index_1]),
copy.copy(index_to_lines_2[index_2]),
effective_cmn_lines_nb=self.min_lines,
)
remove_successives(all_couples)
for cml_stripped_l, cmn_l in all_couples.items():
start_index_1 = cml_stripped_l.fst_lineset_index
start_index_2 = cml_stripped_l.snd_lineset_index
nb_common_lines = cmn_l.effective_cmn_lines_nb
com = Commonality(
cmn_lines_nb=nb_common_lines,
fst_lset=lineset1,
fst_file_start=cmn_l.first_file.start,
fst_file_end=cmn_l.first_file.end,
snd_lset=lineset2,
snd_file_start=cmn_l.second_file.start,
snd_file_end=cmn_l.second_file.end,
)
eff_cmn_nb = filter_noncode_lines(
lineset1, start_index_1, lineset2, start_index_2, nb_common_lines
)
if eff_cmn_nb > self.min_lines:
yield com
def _iter_sims(self) -> Generator[Commonality, None, None]:
"""Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 379 | decoding_stream | ref | function | readlines = decoding_stream(stream, encoding).readlines
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 384 | LineSet | ref | function | LineSet(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 396 | run | def | function | def run(self) -> None:
"""Start looking for similarities and display results on stdout."""
if self.min_lines == 0:
return
self._display_sims(self._compute_sims())
def _compute_sims(self) -> List[Tuple[int, Set[LinesChunkLimits_T]]]:
"""Compute similarities in appended files."""
no_duplicates: Dict[int, List[Set[LinesChunkLimits_T]]] = defaultdict(list)
for commonality in self._iter_sims():
num = commonality.cmn_lines_nb
lineset1 = commonality.fst_lset
start_line_1 = commonality.fst_file_start
end_line_1 = commonality.fst_file_end
lineset2 = commonality.snd_lset
start_line_2 = commonality.snd_file_start
end_line_2 = commonality.snd_file_end
duplicate = no_duplicates[num]
couples: Set[LinesChunkLimits_T]
for couples in duplicate:
if (lineset1, start_line_1, end_line_1) in couples or (
lineset2,
start_line_2,
end_line_2,
) in couples:
break
else:
duplicate.append(
{
(lineset1, start_line_1, end_line_1),
(lineset2, start_line_2, end_line_2),
}
)
sims: List[Tuple[int, Set[LinesChunkLimits_T]]] = []
ensembles: List[Set[LinesChunkLimits_T]]
for num, ensembles in no_duplicates.items():
cpls: Set[LinesChunkLimits_T]
for cpls in ensembles:
sims.append((num, cpls))
sims.sort()
sims.reverse()
return sims
def _display_sims(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> None:
"""Display computed similarities on stdout."""
report = self._get_similarity_report(similarities)
print(report)
def _get_similarity_report(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> str:
"""Create a report from similarities."""
report: str = ""
duplicated_line_number: int = 0
for number, couples in similarities:
report += f"\n{number} similar lines in {len(couples)} files\n"
couples_l = sorted(couples)
line_set = start_line = end_line = None
for line_set, start_line, end_line in couples_l:
report += f"=={line_set.name}:[{start_line}:{end_line}]\n"
if line_set:
for line in line_set._real_lines[start_line:end_line]:
report += f" {line.rstrip()}\n" if line.rstrip() else "\n"
duplicated_line_number += number * (len(couples_l) - 1)
total_line_number: int = sum(len(lineset) for lineset in self.linesets)
report += f"TOTAL lines={total_line_number} duplicates={duplicated_line_number} percent={duplicated_line_number * 100.0 / total_line_number:.2f}\n"
return report
def _find_common(
self, lineset1: "LineSet", lineset2: "LineSet"
) -> Generator[Commonality, None, None]:
"""Find similarities in the two given linesets.
This the core of the algorithm.
The idea is to compute the hashes of a minimal number of successive lines of each lineset and then compare the hashes.
Every match of such comparison is stored in a dict that links the couple of starting indices in both linesets to
the couple of corresponding starting and ending lines in both files.
Last regroups all successive couples in a bigger one. It allows to take into account common chunk of lines that have more
than the minimal number of successive lines required.
"""
hash_to_index_1: HashToIndex_T
hash_to_index_2: HashToIndex_T
index_to_lines_1: IndexToLines_T
index_to_lines_2: IndexToLines_T
hash_to_index_1, index_to_lines_1 = hash_lineset(lineset1, self.min_lines)
hash_to_index_2, index_to_lines_2 = hash_lineset(lineset2, self.min_lines)
hash_1: FrozenSet[LinesChunk] = frozenset(hash_to_index_1.keys())
hash_2: FrozenSet[LinesChunk] = frozenset(hash_to_index_2.keys())
common_hashes: Iterable[LinesChunk] = sorted(
hash_1 & hash_2, key=lambda m: hash_to_index_1[m][0]
)
# all_couples is a dict that links the couple of indices in both linesets that mark the beginning of
# successive common lines, to the corresponding starting and ending number lines in both files
all_couples: CplIndexToCplLines_T = {}
for c_hash in sorted(common_hashes, key=operator.attrgetter("_index")):
for indices_in_linesets in itertools.product(
hash_to_index_1[c_hash], hash_to_index_2[c_hash]
):
index_1 = indices_in_linesets[0]
index_2 = indices_in_linesets[1]
all_couples[
LineSetStartCouple(index_1, index_2)
] = CplSuccessiveLinesLimits(
copy.copy(index_to_lines_1[index_1]),
copy.copy(index_to_lines_2[index_2]),
effective_cmn_lines_nb=self.min_lines,
)
remove_successives(all_couples)
for cml_stripped_l, cmn_l in all_couples.items():
start_index_1 = cml_stripped_l.fst_lineset_index
start_index_2 = cml_stripped_l.snd_lineset_index
nb_common_lines = cmn_l.effective_cmn_lines_nb
com = Commonality(
cmn_lines_nb=nb_common_lines,
fst_lset=lineset1,
fst_file_start=cmn_l.first_file.start,
fst_file_end=cmn_l.first_file.end,
snd_lset=lineset2,
snd_file_start=cmn_l.second_file.start,
snd_file_end=cmn_l.second_file.end,
)
eff_cmn_nb = filter_noncode_lines(
lineset1, start_index_1, lineset2, start_index_2, nb_common_lines
)
if eff_cmn_nb > self.min_lines:
yield com
def _iter_sims(self) -> Generator[Commonality, None, None]:
"""Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 400 | _display_sims | ref | function | self._display_sims(self._compute_sims())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 400 | _compute_sims | ref | function | self._display_sims(self._compute_sims())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 402 | _compute_sims | def | function | def _compute_sims(self) -> List[Tuple[int, Set[LinesChunkLimits_T]]]:
"""Compute similarities in appended files."""
no_duplicates: Dict[int, List[Set[LinesChunkLimits_T]]] = defaultdict(list)
for commonality in self._iter_sims():
num = commonality.cmn_lines_nb
lineset1 = commonality.fst_lset
start_line_1 = commonality.fst_file_start
end_line_1 = commonality.fst_file_end
lineset2 = commonality.snd_lset
start_line_2 = commonality.snd_file_start
end_line_2 = commonality.snd_file_end
duplicate = no_duplicates[num]
couples: Set[LinesChunkLimits_T]
for couples in duplicate:
if (lineset1, start_line_1, end_line_1) in couples or (
lineset2,
start_line_2,
end_line_2,
) in couples:
break
else:
duplicate.append(
{
(lineset1, start_line_1, end_line_1),
(lineset2, start_line_2, end_line_2),
}
)
sims: List[Tuple[int, Set[LinesChunkLimits_T]]] = []
ensembles: List[Set[LinesChunkLimits_T]]
for num, ensembles in no_duplicates.items():
cpls: Set[LinesChunkLimits_T]
for cpls in ensembles:
sims.append((num, cpls))
sims.sort()
sims.reverse()
return sims
def _display_sims(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> None:
"""Display computed similarities on stdout."""
report = self._get_similarity_report(similarities)
print(report)
def _get_similarity_report(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> str:
"""Create a report from similarities."""
report: str = ""
duplicated_line_number: int = 0
for number, couples in similarities:
report += f"\n{number} similar lines in {len(couples)} files\n"
couples_l = sorted(couples)
line_set = start_line = end_line = None
for line_set, start_line, end_line in couples_l:
report += f"=={line_set.name}:[{start_line}:{end_line}]\n"
if line_set:
for line in line_set._real_lines[start_line:end_line]:
report += f" {line.rstrip()}\n" if line.rstrip() else "\n"
duplicated_line_number += number * (len(couples_l) - 1)
total_line_number: int = sum(len(lineset) for lineset in self.linesets)
report += f"TOTAL lines={total_line_number} duplicates={duplicated_line_number} percent={duplicated_line_number * 100.0 / total_line_number:.2f}\n"
return report
def _find_common(
self, lineset1: "LineSet", lineset2: "LineSet"
) -> Generator[Commonality, None, None]:
"""Find similarities in the two given linesets.
This the core of the algorithm.
The idea is to compute the hashes of a minimal number of successive lines of each lineset and then compare the hashes.
Every match of such comparison is stored in a dict that links the couple of starting indices in both linesets to
the couple of corresponding starting and ending lines in both files.
Last regroups all successive couples in a bigger one. It allows to take into account common chunk of lines that have more
than the minimal number of successive lines required.
"""
hash_to_index_1: HashToIndex_T
hash_to_index_2: HashToIndex_T
index_to_lines_1: IndexToLines_T
index_to_lines_2: IndexToLines_T
hash_to_index_1, index_to_lines_1 = hash_lineset(lineset1, self.min_lines)
hash_to_index_2, index_to_lines_2 = hash_lineset(lineset2, self.min_lines)
hash_1: FrozenSet[LinesChunk] = frozenset(hash_to_index_1.keys())
hash_2: FrozenSet[LinesChunk] = frozenset(hash_to_index_2.keys())
common_hashes: Iterable[LinesChunk] = sorted(
hash_1 & hash_2, key=lambda m: hash_to_index_1[m][0]
)
# all_couples is a dict that links the couple of indices in both linesets that mark the beginning of
# successive common lines, to the corresponding starting and ending number lines in both files
all_couples: CplIndexToCplLines_T = {}
for c_hash in sorted(common_hashes, key=operator.attrgetter("_index")):
for indices_in_linesets in itertools.product(
hash_to_index_1[c_hash], hash_to_index_2[c_hash]
):
index_1 = indices_in_linesets[0]
index_2 = indices_in_linesets[1]
all_couples[
LineSetStartCouple(index_1, index_2)
] = CplSuccessiveLinesLimits(
copy.copy(index_to_lines_1[index_1]),
copy.copy(index_to_lines_2[index_2]),
effective_cmn_lines_nb=self.min_lines,
)
remove_successives(all_couples)
for cml_stripped_l, cmn_l in all_couples.items():
start_index_1 = cml_stripped_l.fst_lineset_index
start_index_2 = cml_stripped_l.snd_lineset_index
nb_common_lines = cmn_l.effective_cmn_lines_nb
com = Commonality(
cmn_lines_nb=nb_common_lines,
fst_lset=lineset1,
fst_file_start=cmn_l.first_file.start,
fst_file_end=cmn_l.first_file.end,
snd_lset=lineset2,
snd_file_start=cmn_l.second_file.start,
snd_file_end=cmn_l.second_file.end,
)
eff_cmn_nb = filter_noncode_lines(
lineset1, start_index_1, lineset2, start_index_2, nb_common_lines
)
if eff_cmn_nb > self.min_lines:
yield com
def _iter_sims(self) -> Generator[Commonality, None, None]:
"""Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 406 | _iter_sims | ref | function | for commonality in self._iter_sims():
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 441 | _display_sims | def | function | def _display_sims(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> None:
"""Display computed similarities on stdout."""
report = self._get_similarity_report(similarities)
print(report)
def _get_similarity_report(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> str:
"""Create a report from similarities."""
report: str = ""
duplicated_line_number: int = 0
for number, couples in similarities:
report += f"\n{number} similar lines in {len(couples)} files\n"
couples_l = sorted(couples)
line_set = start_line = end_line = None
for line_set, start_line, end_line in couples_l:
report += f"=={line_set.name}:[{start_line}:{end_line}]\n"
if line_set:
for line in line_set._real_lines[start_line:end_line]:
report += f" {line.rstrip()}\n" if line.rstrip() else "\n"
duplicated_line_number += number * (len(couples_l) - 1)
total_line_number: int = sum(len(lineset) for lineset in self.linesets)
report += f"TOTAL lines={total_line_number} duplicates={duplicated_line_number} percent={duplicated_line_number * 100.0 / total_line_number:.2f}\n"
return report
def _find_common(
self, lineset1: "LineSet", lineset2: "LineSet"
) -> Generator[Commonality, None, None]:
"""Find similarities in the two given linesets.
This the core of the algorithm.
The idea is to compute the hashes of a minimal number of successive lines of each lineset and then compare the hashes.
Every match of such comparison is stored in a dict that links the couple of starting indices in both linesets to
the couple of corresponding starting and ending lines in both files.
Last regroups all successive couples in a bigger one. It allows to take into account common chunk of lines that have more
than the minimal number of successive lines required.
"""
hash_to_index_1: HashToIndex_T
hash_to_index_2: HashToIndex_T
index_to_lines_1: IndexToLines_T
index_to_lines_2: IndexToLines_T
hash_to_index_1, index_to_lines_1 = hash_lineset(lineset1, self.min_lines)
hash_to_index_2, index_to_lines_2 = hash_lineset(lineset2, self.min_lines)
hash_1: FrozenSet[LinesChunk] = frozenset(hash_to_index_1.keys())
hash_2: FrozenSet[LinesChunk] = frozenset(hash_to_index_2.keys())
common_hashes: Iterable[LinesChunk] = sorted(
hash_1 & hash_2, key=lambda m: hash_to_index_1[m][0]
)
# all_couples is a dict that links the couple of indices in both linesets that mark the beginning of
# successive common lines, to the corresponding starting and ending number lines in both files
all_couples: CplIndexToCplLines_T = {}
for c_hash in sorted(common_hashes, key=operator.attrgetter("_index")):
for indices_in_linesets in itertools.product(
hash_to_index_1[c_hash], hash_to_index_2[c_hash]
):
index_1 = indices_in_linesets[0]
index_2 = indices_in_linesets[1]
all_couples[
LineSetStartCouple(index_1, index_2)
] = CplSuccessiveLinesLimits(
copy.copy(index_to_lines_1[index_1]),
copy.copy(index_to_lines_2[index_2]),
effective_cmn_lines_nb=self.min_lines,
)
remove_successives(all_couples)
for cml_stripped_l, cmn_l in all_couples.items():
start_index_1 = cml_stripped_l.fst_lineset_index
start_index_2 = cml_stripped_l.snd_lineset_index
nb_common_lines = cmn_l.effective_cmn_lines_nb
com = Commonality(
cmn_lines_nb=nb_common_lines,
fst_lset=lineset1,
fst_file_start=cmn_l.first_file.start,
fst_file_end=cmn_l.first_file.end,
snd_lset=lineset2,
snd_file_start=cmn_l.second_file.start,
snd_file_end=cmn_l.second_file.end,
)
eff_cmn_nb = filter_noncode_lines(
lineset1, start_index_1, lineset2, start_index_2, nb_common_lines
)
if eff_cmn_nb > self.min_lines:
yield com
def _iter_sims(self) -> Generator[Commonality, None, None]:
"""Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 445 | _get_similarity_report | ref | function | report = self._get_similarity_report(similarities)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 448 | _get_similarity_report | def | function | def _get_similarity_report(
self, similarities: List[Tuple[int, Set[LinesChunkLimits_T]]]
) -> str:
"""Create a report from similarities."""
report: str = ""
duplicated_line_number: int = 0
for number, couples in similarities:
report += f"\n{number} similar lines in {len(couples)} files\n"
couples_l = sorted(couples)
line_set = start_line = end_line = None
for line_set, start_line, end_line in couples_l:
report += f"=={line_set.name}:[{start_line}:{end_line}]\n"
if line_set:
for line in line_set._real_lines[start_line:end_line]:
report += f" {line.rstrip()}\n" if line.rstrip() else "\n"
duplicated_line_number += number * (len(couples_l) - 1)
total_line_number: int = sum(len(lineset) for lineset in self.linesets)
report += f"TOTAL lines={total_line_number} duplicates={duplicated_line_number} percent={duplicated_line_number * 100.0 / total_line_number:.2f}\n"
return report
def _find_common(
self, lineset1: "LineSet", lineset2: "LineSet"
) -> Generator[Commonality, None, None]:
"""Find similarities in the two given linesets.
This the core of the algorithm.
The idea is to compute the hashes of a minimal number of successive lines of each lineset and then compare the hashes.
Every match of such comparison is stored in a dict that links the couple of starting indices in both linesets to
the couple of corresponding starting and ending lines in both files.
Last regroups all successive couples in a bigger one. It allows to take into account common chunk of lines that have more
than the minimal number of successive lines required.
"""
hash_to_index_1: HashToIndex_T
hash_to_index_2: HashToIndex_T
index_to_lines_1: IndexToLines_T
index_to_lines_2: IndexToLines_T
hash_to_index_1, index_to_lines_1 = hash_lineset(lineset1, self.min_lines)
hash_to_index_2, index_to_lines_2 = hash_lineset(lineset2, self.min_lines)
hash_1: FrozenSet[LinesChunk] = frozenset(hash_to_index_1.keys())
hash_2: FrozenSet[LinesChunk] = frozenset(hash_to_index_2.keys())
common_hashes: Iterable[LinesChunk] = sorted(
hash_1 & hash_2, key=lambda m: hash_to_index_1[m][0]
)
# all_couples is a dict that links the couple of indices in both linesets that mark the beginning of
# successive common lines, to the corresponding starting and ending number lines in both files
all_couples: CplIndexToCplLines_T = {}
for c_hash in sorted(common_hashes, key=operator.attrgetter("_index")):
for indices_in_linesets in itertools.product(
hash_to_index_1[c_hash], hash_to_index_2[c_hash]
):
index_1 = indices_in_linesets[0]
index_2 = indices_in_linesets[1]
all_couples[
LineSetStartCouple(index_1, index_2)
] = CplSuccessiveLinesLimits(
copy.copy(index_to_lines_1[index_1]),
copy.copy(index_to_lines_2[index_2]),
effective_cmn_lines_nb=self.min_lines,
)
remove_successives(all_couples)
for cml_stripped_l, cmn_l in all_couples.items():
start_index_1 = cml_stripped_l.fst_lineset_index
start_index_2 = cml_stripped_l.snd_lineset_index
nb_common_lines = cmn_l.effective_cmn_lines_nb
com = Commonality(
cmn_lines_nb=nb_common_lines,
fst_lset=lineset1,
fst_file_start=cmn_l.first_file.start,
fst_file_end=cmn_l.first_file.end,
snd_lset=lineset2,
snd_file_start=cmn_l.second_file.start,
snd_file_end=cmn_l.second_file.end,
)
eff_cmn_nb = filter_noncode_lines(
lineset1, start_index_1, lineset2, start_index_2, nb_common_lines
)
if eff_cmn_nb > self.min_lines:
yield com
def _iter_sims(self) -> Generator[Commonality, None, None]:
"""Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 468 | _find_common | def | function | def _find_common(
self, lineset1: "LineSet", lineset2: "LineSet"
) -> Generator[Commonality, None, None]:
"""Find similarities in the two given linesets.
This the core of the algorithm.
The idea is to compute the hashes of a minimal number of successive lines of each lineset and then compare the hashes.
Every match of such comparison is stored in a dict that links the couple of starting indices in both linesets to
the couple of corresponding starting and ending lines in both files.
Last regroups all successive couples in a bigger one. It allows to take into account common chunk of lines that have more
than the minimal number of successive lines required.
"""
hash_to_index_1: HashToIndex_T
hash_to_index_2: HashToIndex_T
index_to_lines_1: IndexToLines_T
index_to_lines_2: IndexToLines_T
hash_to_index_1, index_to_lines_1 = hash_lineset(lineset1, self.min_lines)
hash_to_index_2, index_to_lines_2 = hash_lineset(lineset2, self.min_lines)
hash_1: FrozenSet[LinesChunk] = frozenset(hash_to_index_1.keys())
hash_2: FrozenSet[LinesChunk] = frozenset(hash_to_index_2.keys())
common_hashes: Iterable[LinesChunk] = sorted(
hash_1 & hash_2, key=lambda m: hash_to_index_1[m][0]
)
# all_couples is a dict that links the couple of indices in both linesets that mark the beginning of
# successive common lines, to the corresponding starting and ending number lines in both files
all_couples: CplIndexToCplLines_T = {}
for c_hash in sorted(common_hashes, key=operator.attrgetter("_index")):
for indices_in_linesets in itertools.product(
hash_to_index_1[c_hash], hash_to_index_2[c_hash]
):
index_1 = indices_in_linesets[0]
index_2 = indices_in_linesets[1]
all_couples[
LineSetStartCouple(index_1, index_2)
] = CplSuccessiveLinesLimits(
copy.copy(index_to_lines_1[index_1]),
copy.copy(index_to_lines_2[index_2]),
effective_cmn_lines_nb=self.min_lines,
)
remove_successives(all_couples)
for cml_stripped_l, cmn_l in all_couples.items():
start_index_1 = cml_stripped_l.fst_lineset_index
start_index_2 = cml_stripped_l.snd_lineset_index
nb_common_lines = cmn_l.effective_cmn_lines_nb
com = Commonality(
cmn_lines_nb=nb_common_lines,
fst_lset=lineset1,
fst_file_start=cmn_l.first_file.start,
fst_file_end=cmn_l.first_file.end,
snd_lset=lineset2,
snd_file_start=cmn_l.second_file.start,
snd_file_end=cmn_l.second_file.end,
)
eff_cmn_nb = filter_noncode_lines(
lineset1, start_index_1, lineset2, start_index_2, nb_common_lines
)
if eff_cmn_nb > self.min_lines:
yield com
def _iter_sims(self) -> Generator[Commonality, None, None]:
"""Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 484 | hash_lineset | ref | function | hash_to_index_1, index_to_lines_1 = hash_lineset(lineset1, self.min_lines)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 485 | hash_lineset | ref | function | hash_to_index_2, index_to_lines_2 = hash_lineset(lineset2, self.min_lines)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 505 | LineSetStartCouple | ref | function | LineSetStartCouple(index_1, index_2)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 506 | CplSuccessiveLinesLimits | ref | function | ] = CplSuccessiveLinesLimits(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 512 | remove_successives | ref | function | remove_successives(all_couples)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 519 | Commonality | ref | function | com = Commonality(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 529 | filter_noncode_lines | ref | function | eff_cmn_nb = filter_noncode_lines(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 536 | _iter_sims | def | function | def _iter_sims(self) -> Generator[Commonality, None, None]:
"""Iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
yield from self._find_common(lineset, lineset2)
def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 542 | _find_common | ref | function | yield from self._find_common(lineset, lineset2)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 544 | get_map_data | def | function | def get_map_data(self):
"""Returns the data we can use for a map/reduce process.
In this case we are returning this instance's Linesets, that is all file
information that will later be used for vectorisation.
"""
return self.linesets
def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py | pylint/checkers/similar.py | 552 | combine_mapreduce_data | def | function | def combine_mapreduce_data(self, linesets_collection):
"""Reduces and recombines data into a format that we can report on.
The partner function of get_map_data()
"""
self.linesets = [line for lineset in linesets_collection for line in lineset]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.