I'm making a function in python that takes an optional parameter *args
. This function calls upon another function passing this optional parameter as well. However, when a certain condition applies, I want the optional parameter to have a certain default value, rather than the value passed in the function call. It is clear in the snippet of code below that simply setting a new value for *args
is incorrect, but what is the correct method of doing this?
def function(arg1, arg2, *args):
if condition:
*args = value
function2(*args)
You could identify your parameter by index in args:
def function(arg1, arg2, *args):
if condition:
args = list(args)
if len(args) == 0: # the second arg in args was not set
args.append("first default")
if len(args) == 1:
args.append("second default")
function2(*args)
But as you see - it's a little ugly. It will involve a lot of if
statements in case you want to use a lot of default positional arguments. Use **kwargs
if you can.
Apparantly *args
is a list, so I had to assign it as args = [value]
, instead of *args = value
. That way it solved the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.