简体   繁体   English

Python 只将非 None 的参数传递给函数

[英]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.我有一个带有四个参数abcd的函数,如下所示。

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 .我需要在这个函数中调用另一个函数myfunc2但只使用用户在myfunc传递的那些参数。 For example, if the user passes values for a and d in myfunc , then I need to call myfunc2 as:例如,如果用户在myfunc传递ad值,那么我需要将myfunc2调用为:

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 ?有没有一种简单的方法来做到这一点,而不是写if的所有可能组合的a,b,c,d

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:如果您想保留函数的调用签名,使用 4 个指定的默认参数,您可以这样做:

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)

You could use dict comprehension to create a dictionary with the not none params and pass it to myfunc2 through unpacking.您可以使用 dict comprehension 创建一个带有 not none 参数的字典,并通过解包将其传递给myfunc2

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM