Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unused function call extension #8732

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
91 changes: 91 additions & 0 deletions pylint/extensions/unassigned_function_call.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt

"""Looks for unassigned function/method calls that have non-nullable return type."""

from __future__ import annotations

from typing import TYPE_CHECKING

import astroid
from astroid import nodes

from pylint.checkers import BaseChecker
from pylint.checkers.typecheck import TypeChecker
from pylint.checkers.utils import only_required_for_messages, safe_infer

if TYPE_CHECKING:
from pylint.lint import PyLinter


class UnusedReturnValueChecker(BaseChecker):
name = "unused_return_value"
msgs = {
"W5486": (
"Function returned value which is never used",
"unused-return-value",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just realized that we have a message for expression that aren't assigned : https://pylint.readthedocs.io/en/stable/user_guide/messages/warning/expression-not-assigned.html. Maybe grouping those two in the same checker and calling this one the same way would make sense:

Suggested change
"unused-return-value",
"function-return-not-assigned",

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review. Docs and examples added, switched to functional tests, message was renamed to function-return-not-assigned.

"Function returns non-nullable value which is never used. "
"Use explicit `_ = func_call()` if you are not interested in returned value",
)
}

@only_required_for_messages("unused-return-value")
def visit_call(self, node: nodes.Call) -> None:
result_is_used = not isinstance(node.parent, nodes.Expr)

if result_is_used:
return

Check warning on line 38 in pylint/extensions/unassigned_function_call.py

View check run for this annotation

Codecov / codecov/patch

pylint/extensions/unassigned_function_call.py#L38

Added line #L38 was not covered by tests

function_node = safe_infer(node.func)
funcs = (nodes.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod)

# FIXME: more elegant solution probably exists
# methods called on instances returned by functions in some libraries
# are having function_node None and needs to be handled here
# for example:
# attrs.evolve returned instances
# instances returned by any pyrsistent method (pmap.set, pvector.append, ...)
if function_node is None:
try:
for n in node.func.infer():
if not isinstance(n, astroid.BoundMethod):
continue

Check warning on line 53 in pylint/extensions/unassigned_function_call.py

View check run for this annotation

Codecov / codecov/patch

pylint/extensions/unassigned_function_call.py#L53

Added line #L53 was not covered by tests
function_node = n
break
except Exception: # pylint:disable=broad-exception-caught
pass

if not isinstance(function_node, funcs):
return

# Unwrap to get the actual function node object
if isinstance(function_node, astroid.BoundMethod) and isinstance(
function_node._proxied, astroid.UnboundMethod
):
function_node = function_node._proxied._proxied

# Make sure that it's a valid function that we can analyze.
# Ordered from less expensive to more expensive checks.
if (
not function_node.is_function
or function_node.decorators
or TypeChecker._is_ignored_function(function_node)
):
return

Check warning on line 75 in pylint/extensions/unassigned_function_call.py

View check run for this annotation

Codecov / codecov/patch

pylint/extensions/unassigned_function_call.py#L75

Added line #L75 was not covered by tests

return_nodes = list(
function_node.nodes_of_class(nodes.Return, skip_klass=nodes.FunctionDef)
)
for ret_node in return_nodes:
if not (
isinstance(ret_node.value, nodes.Const)
and ret_node.value.value is None
or ret_node.value is None
):
self.add_message("unused-return-value", node=node)
return


def register(linter: PyLinter) -> None:
linter.register_checker(UnusedReturnValueChecker(linter))
134 changes: 134 additions & 0 deletions tests/extensions/test_unassigned_function_call.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt

import astroid

from pylint.extensions import unassigned_function_call
from pylint.testutils import CheckerTestCase, MessageTest


class TestUnassignedFunctionCall(CheckerTestCase):
CHECKER_CLASS = unassigned_function_call.UnusedReturnValueChecker

def test_simple_func(self) -> None:
node = astroid.extract_node(
"""
def a():
return 1
a()
""",
)
msg = MessageTest(
msg_id="unused-return-value",
node=node,
line=4,
end_line=4,
col_offset=0,
end_col_offset=3,
)
with self.assertAddsMessages(msg):
self.checker.visit_call(node)

def test_simple_method(self) -> None:
node = astroid.extract_node(
"""
class A:
def return_self(self):
return self
a = A()
a.return_self()
""",
)
msg = MessageTest(
msg_id="unused-return-value",
node=node,
line=6,
end_line=6,
col_offset=0,
end_col_offset=15,
)
with self.assertAddsMessages(msg):
self.checker.visit_call(node)

def test_simple_method_returns_none(self) -> None:
node = astroid.extract_node(
"""
class A:
def return_none(self):
return None
a = A()
a.return_self()
""",
)

with self.assertNoMessages():
self.checker.visit_call(node)

def test_simple_function_returns_none(self) -> None:
node = astroid.extract_node(
"""
def a():
print("doing some stuff")
a()
""",
)

with self.assertNoMessages():
self.checker.visit_call(node)

def test_unassigned_dataclass_replace(self) -> None:
node = astroid.extract_node(
"""
from dataclasses import dataclass, replace

@dataclass
class A:
a: int

inst = A(1)
replace(inst, a=3)
""",
)

msg = MessageTest(
msg_id="unused-return-value",
node=node,
line=9,
end_line=9,
col_offset=0,
end_col_offset=18,
)

with self.assertAddsMessages(msg):
self.checker.visit_call(node)

def test_unassigned_method_call_on_replaced_dataclass_inst(self) -> None:
node = astroid.extract_node(
"""
from dataclasses import dataclass, replace

@dataclass
class A:
a: int

def return_something(self):
return self.a

inst = A(1)
inst = replace(inst, a=3)
inst.return_something()
""",
)

msg = MessageTest(
msg_id="unused-return-value",
node=node,
line=13,
end_line=13,
col_offset=0,
end_col_offset=23,
)

with self.assertAddsMessages(msg):
self.checker.visit_call(node)