[英]Pass empty argument to Python function?
当我正在调用的函数有很多参数并且要有条件地包含一个参数时,我是否必须对该函数进行两次单独的调用,或者有某种方式不传递任何内容(几乎像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)
由于函数是第一类对象,因此您可以将该函数传递给包装器,该包装器将正确构造所需的参数。 这将使该段代码可重用,但也给您带来更大的灵活性,例如需要处理错误。
def wrapper(some_library_func, special=False):
# you could have try catch here if needed.
kwards = {
'first': os.environ['first'],
'second': stuff['second'],
'third': stuff['third'],
'fourth': 'Some Value',
'fifth': False,
'seventh': 'example',
'eighth': True
}
if special:
kwards['sixth'] = 'IMPORTANT_VALUE'
return some_library_func(**kwards)
我看不到使用函数定义变量的方式有什么问题。 您应该在全局范围内声明special_value
,然后在函数顶部包括global special_value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.