Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pass only parameters which are not None to a function

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?

like image 443
S_S Avatar asked Jun 07 '26 00:06

S_S


2 Answers

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)
like image 93
Marcos Blandim Avatar answered Jun 08 '26 12:06

Marcos Blandim


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)
like image 33
Paul Cornelius Avatar answered Jun 08 '26 13:06

Paul Cornelius