传递函数将忽略的参数

时间:2019-11-20 07:55:35

标签: python dictionary default-value

假设我们有一个带有签名的简单python函数:

def foo(first, second, third=50)

当我从main调用它时,我将始终具有第一个和第二个参数,但并不总是具有第三个参数。

当我尝试从字典中获取第三个字典时,我使用了:third = dict['value'] if 'value' in dict.keys() else None

问题在于,当我传递此None时,我希望函数使用其默认的第三个参数,即50,但仅使用None。我也尝试过[]

是否有一种更优雅的方法来执行此操作,除了两次调用该函数外,还取决于是否存在third,一次使用它,一次不使用它,如下所示?

third = dict['value'] if 'value' in dict.keys() else None
if third:
    foo(first, second, third)
else:
    foo(first, second)

6 个答案:

答案 0 :(得分:2)

您可以这样做:

kwargs = {'third': dict['value']} if 'value' in dict else {}
foo(first, second, **kwargs)

第一行创建一个kwargs字典,如果third中有value,则该字典仅包含键dict,否则为空。并且在调用该函数时,您可以传播该kwargs字典。

答案 1 :(得分:1)

Python中的函数对象具有特殊的属性__defaults__。这是具有默认参数值的元组。因此,您可以从此处轻松获取third的默认值:

def foo(first, second, third=50):
    return third

dict = {}
print(foo(10, 20, dict.get('value', foo.__defaults__[0])))  # prints 50

dict = {"value": 100}
print(foo(10, 20, dict.get('value', foo.__defaults__[0])))  # prints 100

答案 2 :(得分:0)

尝试:

if dict.get('value'):
    def foo(first, second, third)
else:
    def foo(first, second)

答案 3 :(得分:0)

如何像这样重新定义函数:

def foo(first, second, third):
    if third == None:
        third = 50
    """ Your code here """

third = dict['value'] if 'value' in dict.keys() else 50

答案 4 :(得分:0)

您可以使用列表理解将args分组:

def foo(first,second,third=50): 
    print(first,second,third) 

args=[ a for a in [10,20,d.get("third",None)] if a!=None ]

foo(*args)                                                                                                           
10 20 50

答案 5 :(得分:0)

我今天有一个类似的问题。调用函数时,请执行以下操作:

foo(first, second, third=50)

当这样传递时,三分之一应该取值。

您可以检查第三次通过了

if None in third:
    # do this
else:
    # do something else
相关问题