当我调用的函数有很多参数时,我想有条件地包含一个,我是否必须对函数进行两次单独的调用,或者是否有某种方式不传递任何参数(几乎像 None
) 这样我就不会为特定参数传递任何参数?
例如,有时我想为参数 sixth
传递参数,但其他时候我想不为该参数传递任何内容。这段代码有效,但我感觉我复制的内容超出了我应该复制的范围。
我正在调用的函数位于第三方库中,因此我无法更改它处理接收到的参数的方式。如果我为 sixth
传入 None
,该函数会引发异常。我需要传递我的 'IMPORTANT_VALUE'
或不传递任何内容。
我目前在做什么:
def do_a_thing(stuff, special=False):
if special:
response = some.library.func(
first=os.environ['first'],
second=stuff['second'],
third=stuff['third']
fourth='Some Value',
fifth=False,
sixth='IMPORTANT_VALUE',
seventh='example',
eighth=True
)
else:
response = some.library.func(
first=os.environ['first'],
second=stuff['second'],
third=stuff['third']
fourth='Some Value',
fifth=False,
seventh='example',
eighth=True
)
return response
我想做什么:
def do_a_thing(stuff, special=False):
special_value = 'IMPORTANT_VALUE' if special else EMPTY_VALUE
response = some.library.func(
first=os.environ['first'],
second=stuff['second'],
third=stuff['third']
fourth='Some Value',
fifth=False,
sixth=special_value,
seventh='example',
eighth=True
)
return response
最佳答案
一个解决方案是构建一个字典,其中包含您要传递给函数的值,并根据 special
值进行修改。然后使用 python unpacking将其扩展为要调用的函数的命名参数列表:
def do_a_thing(stuff, special=False):
kwargs = dict(
first=os.environ['first'],
second=stuff['second'],
third=stuff['third']
fourth='Some Value',
fifth=False,
seventh='example',
eighth=True
)
if special:
kwargs['sixth'] = 'IMPORTANT_VALUE'
return some.library.func(**kwargs)
关于python - 将空参数传递给 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951629/