Using default arguments in a function with variable arguments. Is this possible?

Viewed 106

I have the following piece of code. In this, I want to make use of the optional parameter given to 'a'; i.e '5', and not '1'. How do I make the tuple 'numbers' contain the first element to be 1 and not 2?

def fun_varargs(a=5, *numbers, **dict):
    print("Value of a is",a)
    for i in numbers:
        print("Value of i is",i)
    for i, j in dict.items():
        print("The value of i and j are:",i,j)

fun_varargs(1,2,3,4,5,6,7,8,9,10,Jack=111,John=222,Tom=333)
3 Answers

The "idiomatic" Python way to do this is to have the optional argument default to None.

def fun_varargs(a=None, *numbers, **dict):
  if a is None:
    a = 5
  ...

Then you can explicitly choose not to pass it.

fun_varargs(None, 1, 2, 3, 4, 5, some_keyword_arg=":)")

I don't know of a way to actually choose not to pass an optional argument. If you're looking for a practical solution, this is the way to go. But if there's some deeper hackery that lets you bypass the argument altogether, I'd be interested in seeing it as well.

The .__defaults__ attributes provides default arguments in a tuple. You can use that for here.

>>> def fun_varargs(a = 5, *numbers, **dict):
...     print("value of a is", a)
...     for i in numbers:
...             print("value of i is", i)
...     for i, j in dict.items():
...             print("The value of i and j are:", i,j)
... 

>>> fun_varargs(fun_varargs.__defaults__[0],1,2,3,4,5,6,7,8,9,10,Jack=111,John=222,Tom=333)
value of a is 5
value of i is 1
value of i is 2
value of i is 3
value of i is 4
value of i is 5
value of i is 6
value of i is 7
value of i is 8
value of i is 9
value of i is 10
The value of i and j are: Jack 111
The value of i and j are: John 222
The value of i and j are: Tom 333

One option is to move a after *numbers

def fun_varargs(*numbers, a=5, **dict):
    ...

However, you can no longer use it as a positional argument. fun_varargs(42) would not set a to 42. You can only define a using keyword argument, ie fun_varargs(a=42).

Related