S_S
S_S

Reputation: 1402

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?

Upvotes: 8

Views: 12321

Answers (3)

Marcos Blandim
Marcos Blandim

Reputation: 383

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)

Upvotes: 15

user24992517
user24992517

Reputation: 21

You can also use locals():

def myfunc(a=None,b=None,c=None,d=None):
    not_none_params = {k:v for k, v in locals().items() if v is not None}
    myfunc2(**not_none_params)

Note: locals() will return a dict with all the local variables to your function so if you define a variable before calling it, it will also be inside the dict. eg:

def myfunc(a=None,b=None,c=None,d=None):
    d = "bla"
    not_none_params = {k:v for k, v in locals().items() if v is not None}
    myfunc2(**not_none_params)

d = "bla" will also be passed as parameter to myfunc2

Upvotes: 2

Paul Cornelius
Paul Cornelius

Reputation: 10946

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)

Upvotes: 7

Related Questions