I have a function with four parameters a, b, c and d as shown below.
def myfunc(a=None,b=None,c=None,d=None):
if <check which are not None>:
myfunc2(<pass those which are not None>)
I need to call another function myfunc2 inside this function but with only those parameters which the user has passed in myfunc. For example, if the user passes values for a and d in myfunc, then I need to call myfunc2 as:
myfunc2(a=a, d=d)
Is there a simple way to do this rather than write if cases for all possible combinations of a,b,c,d?
You could use Dict Comprehensions to create a dictionary with the not None params and pass it to myfunc2 through unpacking.
def myfunc(a=None,b=None,c=None,d=None):
params = {
"a": a,
"b": b,
"c": c,
"d": d,
}
not_none_params = {k:v for k, v in params.items() if v is not None}
myfunc2(**not_none_params)
def myfunc(**kwargs):
myfunc2(**{k:v for k, v in kwargs.items() if v is not None})
If you want to preserve the function's call signature, with the 4 specified default arguments, you can do this:
def myfunc(a=None, b=None, c=None, d=None):
def f(**kwargs):
return myfunc2(**{k:v for k, v in kwargs.items() if v is not None})
return f(a=a, b=b, c=c, d=d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With