Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a default for star arguments?

I have a function that accepts *args, but I would like to set a default tuple, in case none are provided. (This is not possible through def f(*args=(1, 3, 5)), which raises a SyntaxError.) What would be the best way to accomplish this? The intended functionality is shown below.

f()
# I received 1, 2, 3!

f(1)
# I received 1!

f(9, 3, 72)
# I received 9, 3, 72!

The following function g will provide the correct functionality, but I would prefer *args.

def g(args=(1, 2, 3)):
    return "I received {}!".format(', '.join(str(arg) for arg in args))

g()
# I received 1, 2, 3!

g((1,))
# I received 1!

g((9, 3, 72))
# I received 9, 3, 72!
like image 459
2Cubed Avatar asked Nov 29 '22 09:11

2Cubed


1 Answers

You could check whether args are truthy in your function:

def g(*args):
    if not args:
        args = (1, 2, 3)
    return "I received {}!".format(', '.join(str(arg) for arg in args))

If no args are passed to the function, it will result in a empty tuple, which evaluates to False.

like image 104
Railslide Avatar answered Dec 06 '22 20:12

Railslide