感谢this SO post我现在知道如何将字典作为 kwargs 传递给函数(如果我重复调用函数,则可以节省一些空间)。
我想知道是否仍然可以以某种方式专门“覆盖”字典中传递的参数之一?如果我有 100 个函数调用,其中我传递了 kwarg-dict,并且在其中一个函数调用中我需要更改其中一个 kwarg 参数,有没有一种好的方法可以做到这一点?
一个解决方案是“手动”编写该调用的所有参数,而不是使用 kwarg-dict,但我特别希望以一种优雅的方式覆盖参数。
最小示例:
def func(arg1="foo", arg_a= "bar", firstarg=1):
print(arg1, arg_a, firstarg)
kwarg_dictionary = {
'arg1': "foo",
'arg_a': "bar",
'first_arg':42
}
# normal call, works - without overwriting any args
func(**kwarg_dictionary)
# The following fails with TypeError: func() got multiple values for keyword argument 'first_arg'
func(**kwarg_dictionary, first_arg=100)
# The following works, but is very clunky and long:
func(**({k:v for k, v in kwarg_dictionary.items() if k != 'first_arg'}), first_arg=54)
尝试使用 functools.partial
解决该问题也被证明收效甚微,因为它期望参数按顺序排列,而您无法提供关键字参数。
我想知道是否有比最后一行代码更优雅的解决方案?
最佳答案
kwargs 重写的示例
def func(arg1="foo", arg_a="bar", first_arg=0):
print(arg1, arg_a, first_arg)
kwarg_dictionary = {
'arg1': "foo",
'arg_a': "bar",
'first_arg': 0
}
# Normal call, works without overwriting any args
func(**kwarg_dictionary)
# foo bar 0
# Create a modified dictionary by updating the value
kwargs1 = dict(kwarg_dictionary, first_arg=1)
func(**kwargs1)
# foo bar 1
# Create a modified dictionary by merging (unpacking)
kwargs2 = {**kwarg_dictionary, **{"first_arg": 2}}
func(**kwargs2)
# foo bar 2
# Create a modified dictionary by copy
kwargs3 = kwarg_dictionary.copy()
kwargs3['first_arg'] = 3
func(**kwargs3)
# foo bar 3
# Make sure the original kwargs haven't been modified
print(kwarg_dictionary)
# {'arg1': 'foo', 'arg_a': 'bar', 'first_arg': 0}
关于python - 通过 dict 将 kwargs 传递给函数并以优雅的方式覆盖单个传递的 kwarg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76345708/