2

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?

1
  • Yes, do rename it to something better, if possible. Many times you just want a function to take an arbitrary amount of arguments that isn't one specific type of thing, and in that case *args is an acceptable name. I think it's these examples you've seen. Nov 27, 2020 at 3:12

2 Answers 2

3

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)
1

If it helps people understand your code, I don't see a reason not to do it. Just don't over do it.

The Python standard library does this sometimes, here's a random example: heapq.merge - https://github.com/python/cpython/blob/c8aaf71dde4888864c0c351e2f935f87652c3d54/Lib/heapq.py#L314 . Though in the overwhelming majority of cases they use *args. Looking around the Django source code, they use *something about 60 times, and 35 of them are *args.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.