简体   繁体   English

如果不为null,则将参数传递给方法

[英]Passing argument to a method if not null

How do i include argument in python only if its not null? 仅当参数不为null时,如何在python中包含参数? Following code works fine if i pass valid color to method doSomething. 如果我将有效颜色传递给方法doSomething,则以下代码可以正常工作。 Now color is sometimes null (like null in java, i guess its None or nil in python), whic is when printColor throws exception. 现在color有时为null(就像java中的null,我猜它在Python中为None或nil),而在printColor抛出异常时。 How can i avoid this? 我如何避免这种情况?

Invalid type for parameter packageNamespace, value: None

response = client.printColor(
            color = color # Only include this param is not None/Null
   )

response = client.printColor() # this works

You can filter None s out of a dict: 您可以从字典中筛选出None

kwargs = {
    'color': color,
    ⋮
}

response = client.printColor(**{k: v for k, v in kwargs.items() if v is not None})

Or do the same thing as a function: 或做与函数相同的事情:

def none_to_default(**kwargs):
    return {k: v for k, v in kwargs.items() if v is not None}


client.printColor(**none_to_default(
    color=color,
    ⋮
))

This might not be the best solution to the problem, though. 但是,这可能不是解决问题的最佳方法。 It would be ideal if you could show the real function['s documentation]. 如果您可以显示真实的函数[的文档],那将是理想的。

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

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