如果kwargs中的键与函数关键字冲突怎么办?



在类似

的函数中
def myfunc(a, b, **kwargs):
    do someting

如果传入的命名参数已经包含关键字"a",则调用将失败。

目前我需要从其他地方用字典调用myfunc(所以我不能控制字典的内容),如

myfunc(1,2, **dict)

如何确保没有冲突?如果有,解决办法是什么?

如果有任何方法编写一个装饰器来解决这个问题,因为这可能是一个常见的问题?

如果你的函数从其他地方获取一个实际的字典,你不需要使用**传递它。只需像普通参数一样传递字典:

def myfunc(a, b, kwargs):
    # do something
myfunc(1,2, dct) # No ** needed

如果myfunc被设计为接受任意数量的关键字参数,则只需要使用**kwargs。这样的:

myfunc(1,2, a=3, b=5, something=5)

如果你只是传递一个字典,它是不需要的。

如果这是一个严重的问题,不要命名你的论点。只需使用splat参数:

def myfunc(*args, **kwargs):
    ...

并手动解析args

2件事:

  • 如果myfunc(1,2, **otherdict)从其他地方被调用,你无法控制otherdict中的内容-你无能为力,他们错误地调用了你的函数。调用函数需要保证没有冲突

  • 如果您是呼叫函数…然后你只需要自己合并字典。例如:

x

otherdict = some_called_function()`
# My values should take precedence over what's in the dict
otherdict.update(a=1, b=2)
# OR i am just supplying defaults in case they didn't
otherdict.setdefault('a', 1)
otherdict.setdefault('b', 2)
# In either case, then i just use kwargs only.
myfunc(**otherdict)

最新更新