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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With