In python, how can I call a function using the default value of an argument? I know it can be done just not passing the parameter when you call the function, but I would prefer to pass the variable through the function though. Having these two functions:
def A(argA1=defValA1, argA2=defValA2, argA3=defValA3):
argB1val=K*argA1
argB2val=K*argA2
argB3val=K*argA3
B(argB1=argB1val, argB2=argB2val,argB3=argB3val)
def B(argB1=defValB1, argB2=defValB2, argB3=defValB3):
print("First argument: "+argB1)
print("Second argument: "+argB2)
print("Third argument: "+argB3)
If I call A() with all the arguments, there’s no problem:
Main:
A(argA1val, argA2val, argA3val)
But what if I call A() with some missing arguments?:
Main:
A(argA1val)
In this case, inside the A() function
B() will be called taking the default values for the last two:
B(argB1= K*argA1, argB2= K* defValA2, argB3= K* defValA3)
However, I’d like to call B() using the default values of their last two arguments, something like :
B(argB1= K*argA1, argB2=defValB2, argB3=defValB3)
So, I would like A() to be something like:
def A(argA1=defValA1, argA2=defValA2, argA3=defValA3):
if (argA1==defValA1):
argB1val=B.getDefaultValue("argB1")
else:
argB1val=K*argA1
if (argA2==defValA2):
argB2val=B.getDefaultValue("argB2")
else:
argB2val=K*argA2
if (argA3==defValA3):
argB3val=B.getDefaultValue("argB3")
else:
argB3val=K*argA3
B(argB1=argB1val,argB2=argB2val,argB3=argB3val)
Otherwise, I’d need to do something like:
def A(argA1=defValA1, argA2=defValA2, argA3=defValA3):
if (argA1==defValA1 && argA2!=defValA2 && argA3!=defValA3):
argB2val=K*argA2
argB3val=K*argA3
B(argB1= defValB1, argB2=argB2val,argB3=argB3val)
if (argA1!=defValA1 && argA2==defValA2 && argA3!=defValA3):
argB1val=K*argA1
argB3val=K*argA3
B(argB1=argB1val, argB2= defValB2,argB3=argB3val)
if (argA1!=defValA1 && argA2!=defValA2 && argA3==defValA3):
argB1val=K*argA1
argB2val=K*argA2
B(argB1= argB1val, argB2=argB2val,argB3= defValB1)
if (argA1==defValA1 && argA2==defValA2 && argA3!=defValA3):
argB3val=K*argA3
B(argB1= defValA1, argB2= defValA2,argB3=argB3val)
….
….
….
Etc…
Having even a lot more combinations if we have more parameters.
Anyone knows if there’s a way to get the default value of a parameter to be passed in a function?
Thanks!
defValA1
,defValA2
,defValA3
) for the params ofA
, aren't appropriate enough to serve as default values, when you get to the part where you compute the args for invokingB
from withinA
. A true default would be default in every sense. As suggested by @MatiasCicero, you might as well use some other values (such asNone
) as the defaults, in the place ofdefValA1
,defValA2
, anddefValA3
.