Let's say I have a function f()
which I know accepts 1 argument, action
, followed by a variable number of arguments.
Depending on the initial action
value, the function expects a different set of following arguments, e.g. for action 1
we know we must have 3 extra arguments p1
, p2
and p3
. Depending on how the function was called, these args can be either in args
or `kwargs.
How do I retrieve them?
def f(action, *args, **kwargs):
if action==1:
#we know that the function should have 3 supplementary arguments: p1, p2, p3
#we want something like:
#p1 = kwargs['p1'] OR args[0] OR <some default> (order matters?)
#p1 = kwargs['p1'] OR args[0] OR <some default>
#p1 = kwargs['p1'] OR args[0] OR <some default>
Note that:
f(1, 3, 4, 5)
f(1,p1=3, p2=4, p3=5)
f(1, 2, p2=4, p3=5)
will place the different p1
, p2
, p3
parameters in either args
or kwargs
. I could try with nested try/except statements, like:
try:
p1=kwargs['p1']
except:
try:
p1=args[0]
except:
p1=default
but it does not feel right.