Reputation: 378
For my code in Python, I would like to call many functions with a specific argument. However, for some functions, that argument does not do anything. Still, I would like to add the argument for compatibility reasons. For example, consider the following minimal working example:
def my_function(unused=False):
""" Function with unused argument. """
return True
Obviously, the argument unused
is not used, so Pylint throws a warning:
W0613: Unused argument 'redundant' (unused-argument)
My point is that I do not want to remove the argument unused
, because the function my_function
will be called in a similar way as many other functions for which unused
is used.
My question: How can I avoid the warning from Pylint without removing the optional argument?
Option 1: I can think of two options, but these options do not satisfy me. One option is to add some useless code, such that unused
is used, e.g.,
def my_function(unused=False):
""" Function with unused argument. """
if unused:
dummy = 10
del dummy
return True
This feels as a waste of resources and it only clutters the code.
Option 2: The second option is to suppress the warning, e.g., like this:
def my_function(unused=False):
""" Function with unused argument. """
# pylint: disable=unused-argument
return True
I also do not really like this option, because usually Pylint warnings are a sign of bad style, so I am more looking to a different way of coding that avoids this warning.
What other options do I have?
Upvotes: 24
Views: 21597
Reputation: 22245
It would be possible to work out a solution by playing around with **kwargs
. For example:
def _function_a(one, two=2):
return one + two
def _function_b(one, **kwargs):
return one + kwargs['two']
def _function_c(one, **_kwargs):
return one
def _main():
for _function in [_function_a, _function_b, _function_c]:
print(_function.__name__, _function(1, two=4))
Upvotes: 3
Reputation: 22245
I do not believe disabling some pylint warnings is bad style, as long as it is done carefully with clear intent and as specific as possible. For this purpose it is important to activate the useless-suppression
check. When it is active pylint will warn you if some messages are locally disabled for no good reason. Add this to your .pylintrc
:
[MESSAGES CONTROL]
enable=useless-suppression
For example I would recommend disabling the exact occurrence of the issue like in the following example:
def my_function(
used,
unused=False, # pylint: disable=unused-argument
):
""" Function with unused argument. """
return used
Adding a leading underscore should also keep pylint from triggering:
def my_function(used, _unused=False):
""" Function with unused argument. """
return used
Another commonly used pattern is the following:
def my_function(used, unused_a, unused_b=False):
""" Function with unused argument. """
_ = (unused_a, unused_b,)
return used
Upvotes: 26