Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, can I specify a function argument's default in terms of other arguments?

Suppose I have a python function that takes two arguments, but I want the second arg to be optional, with the default being whatever was passed as the first argument. So, I want to do something like this:

def myfunc(arg1, arg2=arg1):     print (arg1, arg2) 

Except that doesn't work. The only workaround I can think of is this:

def myfunc(arg1, arg2=None):     if arg2 is None:         arg2 = arg1     print (arg1, arg2) 

Is there a better way to do this?

like image 269
Ryan C. Thompson Avatar asked Jan 01 '11 19:01

Ryan C. Thompson


People also ask

Can you set default values to Python arguments?

In addition to passing arguments to functions via a function call, you can also set default argument values in Python functions. These default values are assigned to function arguments if you do not explicitly pass a parameter value to the given argument. Parameters are the values actually passed to function arguments.

Can we have default arguments in functions if so how in Python?

Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.

Can functions have default arguments?

In C++ programming, we can provide default values for function parameters. If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.

Can you specify argument type in Python?

5 Types of Arguments in Python Function Definition:keyword arguments. positional arguments. arbitrary positional arguments. arbitrary keyword arguments.


1 Answers

As @Ignacio says, you can't do this. In your latter example, you might have a situation where None is a valid value for arg2. If this is the case, you can use a sentinel value:

sentinel = object() def myfunc(arg1, arg2=sentinel):     if arg2 is sentinel:         arg2 = arg1     print (arg1, arg2)  myfunc("foo")           # Prints 'foo foo' myfunc("foo", None)     # Prints 'foo None' 
like image 171
moinudin Avatar answered Oct 23 '22 16:10

moinudin