Search code examples
pythoncoding-stylepylintoptional-arguments

Python: unused argument needed for compatibility. How to avoid Pylint complaining about it


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?


Solution

  • 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