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

2024-09-27 07:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

像这样的函数

def myfunc(a, b, **kwargs):
    do someting

如果我传入的命名参数已经有关键字“a”,则调用将失败。在

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

^{pr2}$

如何确保不发生冲突?如果有,有什么解决办法?在

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


Tags: 函数内容参数字典def地方关键字myfunc
3条回答

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

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

并手动解析args。在

2件事:

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

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

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)

如果您的函数是从其他地方获取实际dict,则不需要使用**传递它。就像一个普通的论据一样传递口述:

def myfunc(a, b, kwargs):
    # do something

myfunc(1,2, dct) # No ** needed

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

^{pr2}$

如果你只是给它一个口述,那就不需要了。在

相关问题 更多 >

    热门问题