Search code examples
pythonargs

Python give another name instead of `*args` for readability is good practice?


So there is *args in python where you can give arbitrary number of arguments to a function. Lets say I've created the following code

def example_sum(*args):
    return sum(args)

And when i'm trying to use it in my editor(VS code), it hints the function parameter like the following

(*args)

Now for more easier to understand my code, I want to name the *args to something else. And I just found out that you can indeed rename it.

def example_sum(*numbers_to_sum):
    return sum(numbers_to_sum)

But the thing is I don't think I've seen other programmers rename this. So was wondering if it was a good practice?


Solution

  • The short answer is that it really depends on the functionality of your function.

    Note that because *args and **kwargs is the standard convention, in some cases, it may be best to just leave them as such as they are immediately recognizable and familiar to anyone who may be reading your code.

    The example you provided is a perfect example of when the names can be changed. Keep in mind, the general rule of thumb is that it should still easily convey its purpose:

    def sum_nums(*numbers):
        ...
    

    Changing *args to *numbers is perfectly valid here - the intention is still blatantly obvious.

    An example where it might actually be best to change the names is when creating the wrapper function in a decorator:

    def my_decorator(func):
        def wrapper(*func_args, **func_kwargs):
            ...
            return func(*func_args, **func_kwargs)
        return wrapper
    

    The use of *func_args and *func_kwargs makes it clear that the arguments that are passed here are from the function.

    Even the Python docs will occasionally change the name to something more fitting. For example, the built-in function, zip, does not use *args:

    zip(*iterables)