Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)
like image 630
Karthik Bhat Avatar asked Dec 29 '18 06:12

Karthik Bhat


People also ask

What is the difference between default values and default arguments?

If a function is called by passing argument/s, those arguments are used by the function. But if the argument/s are not passed while invoking a function then, the default values are used. Default value/s are passed to argument/s in the function prototype.

What is the use of default argument in Python?

The idea behind default argument is simple. If a function is called by passing argument/s, those arguments are used by the function. But if the argument/s are not passed while invoking a function then, the default values are used. Default value/s are passed to argument/s in the function prototype.

What are the default arguments in C++?

The default arguments are used when you provide no arguments or only few arguments while calling a function. The default arguments are used during compilation of program.

How to assign default values to arguments in a form?

The default value is assigned by using the assignment (=) operator of the form keywordname =value. Let’s understand this through a function student. The function student contains 3-arguments out of which 2 arguments are assigned with default values.


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

like image 194
Silvio Mayolo Avatar answered Sep 28 '22 17:09

Silvio Mayolo