Python 如果kwargs中的键与function关键字冲突怎么办

Python 如果kwargs中的键与function关键字冲突怎么办,python,keyword-argument,Python,Keyword Argument,在函数中,如 def myfunc(a, b, **kwargs): do someting 如果我传入的命名参数已经有关键字“a”,则调用将失败 目前我需要从其他地方使用字典调用myfunc(因此我无法控制字典的内容),如 如何确保没有冲突?如果有,解决办法是什么 如果有什么方法可以编写一个装饰程序来解决这个问题,因为这可能是一个常见的问题?如果这是一个严重的问题,不要说出你的论点。只需使用splat参数: def myfunc(*args, **kwargs): ...

在函数中,如

def myfunc(a, b, **kwargs):
    do someting
如果我传入的命名参数已经有关键字“a”,则调用将失败

目前我需要从其他地方使用字典调用myfunc(因此我无法控制字典的内容),如

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


如果有什么方法可以编写一个装饰程序来解决这个问题,因为这可能是一个常见的问题?

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

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

并手动解析
args

如果您的函数从其他地方获取实际的dict,则不需要使用
**
传递它。只需像普通参数一样传递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)
如果你只是通过口述,就不需要了。

2件事:

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

  • 如果您是调用函数。。。然后你只需要自己合并这些命令。i、 e:

x


另一种选择是将位置参数混淆为不太可能被偶然击中的内容,例如
def myfunc(\uuu a,\uu b,**kwargs):…
。请参阅以了解其工作原理。
myfunc(1,2, a=3, b=5, something=5)
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)