如果kwargs中的键与函数参数冲突会怎样?

4 投票
3 回答
1662 浏览
提问于 2025-04-18 16:47

在一个像这样的函数中:

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

如果我传入的命名参数中已经有一个关键词是“a”,那么这个调用就会失败。

目前我需要用一个来自其他地方的字典来调用myfunc(所以我无法控制这个字典的内容),就像这样:

myfunc(1,2, **dict)

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

有没有办法写一个装饰器来解决这个问题,因为这可能是一个常见的问题?

3 个回答

0

有两件事:

  • 如果 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)
3

如果你的函数是从其他地方拿到一个字典(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

如果这个问题真的很严重,那就别给你的参数起名字。直接使用“星号参数”(splat arguments)就行了:

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

然后手动解析 args

撰写回答