在给定条件的情况下,在 Python 中是否有一种简洁的(pythonic?)方法来使用命名参数默认值?
Is there a neat (pythonic?) way to use named parameter defaults in Python given a condition?
我有一个带有一些命名参数的函数,以及一个包含具有这些名称的键以及其他一些键的字典。我想用字典中的值调用函数。
- 我不能使用
**data
因为 Python 会因为额外的键而引发 TypeError: unexpected keyword argument
。
- 字典可能不包含某些键,所以我无法在不检查它们是否存在的情况下引用键(而且我不想传递
get
的默认值)。
- 我无法重写该函数,因为它在一个单独的库中。
如何只解压与函数参数匹配的密钥?
def do_something(arg1=None, arg2=''):
...
data = {'arg1': 1, 'arg2': 2, 'other': 3}
# doesn't work if key doesn't exist
do_something(arg1=data['arg1'], arg2=data['arg2'])
# too verbose, hard to extend
if 'arg1' in data:
do_something(arg1=data['arg1'], arg2=data['arg2'])
else:
do_something(arg2=data['arg2'])
这里只是即兴演奏...
do_something(**{ k: data[k] for k in ['Arg1', 'Arg2'] if k in data })
虽然看起来很讨厌。
或者,我只是从我的一个项目中挖掘出来的
def call_with_optional_arguments(func, **kwargs):
'''
calls a function with the arguments **kwargs, but only those that the function defines.
e.g.
def fn(a, b):
print a, b
call_with_optional_arguments(fn, a=2, b=3, c=4) # because fn doesn't accept `c`, it is discarded
'''
import inspect
function_arg_names = inspect.getargspec(func).args
for arg in kwargs.keys():
if arg not in function_arg_names:
del kwargs[arg]
func(**kwargs)
在你的情况下,它可以像这样使用:
call_with_optional_arguments(do_something, **data)
--
(如果您想知道这个名称,我用它来触发我的库的用户将传入的回调函数。'optional' 在这种情况下意味着 func
不会必须接受我调用的所有参数)
我有一个带有一些命名参数的函数,以及一个包含具有这些名称的键以及其他一些键的字典。我想用字典中的值调用函数。
- 我不能使用
**data
因为 Python 会因为额外的键而引发TypeError: unexpected keyword argument
。 - 字典可能不包含某些键,所以我无法在不检查它们是否存在的情况下引用键(而且我不想传递
get
的默认值)。 - 我无法重写该函数,因为它在一个单独的库中。
如何只解压与函数参数匹配的密钥?
def do_something(arg1=None, arg2=''):
...
data = {'arg1': 1, 'arg2': 2, 'other': 3}
# doesn't work if key doesn't exist
do_something(arg1=data['arg1'], arg2=data['arg2'])
# too verbose, hard to extend
if 'arg1' in data:
do_something(arg1=data['arg1'], arg2=data['arg2'])
else:
do_something(arg2=data['arg2'])
这里只是即兴演奏...
do_something(**{ k: data[k] for k in ['Arg1', 'Arg2'] if k in data })
虽然看起来很讨厌。
或者,我只是从我的一个项目中挖掘出来的
def call_with_optional_arguments(func, **kwargs):
'''
calls a function with the arguments **kwargs, but only those that the function defines.
e.g.
def fn(a, b):
print a, b
call_with_optional_arguments(fn, a=2, b=3, c=4) # because fn doesn't accept `c`, it is discarded
'''
import inspect
function_arg_names = inspect.getargspec(func).args
for arg in kwargs.keys():
if arg not in function_arg_names:
del kwargs[arg]
func(**kwargs)
在你的情况下,它可以像这样使用:
call_with_optional_arguments(do_something, **data)
--
(如果您想知道这个名称,我用它来触发我的库的用户将传入的回调函数。'optional' 在这种情况下意味着 func
不会必须接受我调用的所有参数)