当在python函数中使用* args,** kwargs时,“为关键字参数获取了多个值”

时间:2013-12-15 22:47:43

标签: python python-2.7 kwargs

将命名参数request传递给**kwargs时,我收到错误消息 -

Traceback (most recent call last):
  File "testKwargs.py", line 9, in <module>
    load_strategy(request="myReq", backend="myBackend", redirect_uri=None, *args, **kwargs)
  File "testKwargs.py", line 5, in load_strategy
    get_strategy("backends", "strategy", "storage", *args, **kwargs)
TypeError: get_strategy() got multiple values for keyword argument 'request'

testKwargs.py中的代码位于 -

之下
def get_strategy(backends, strategy, storage, request=None, backend=None, *args, **kwargs):
    print request

def load_strategy(*args, **kwargs):
    get_strategy("backends", "strategy", "storage", *args, **kwargs)

args = ([],)
kwargs = {"acess_token":"myAccToken", "id":"myId"}
load_strategy(request="myReq", backend="myBackend", redirect_uri=None, *args, **kwargs)

我原以为request **kwargs中的密钥load_strategy会有一个键值对传递给request get_stragegy参数{1}},但情况似乎并非如此。

我想弄清楚我在这里缺少什么。

1 个答案:

答案 0 :(得分:4)

您正在传递额外位置参数:

args = ([],)

该元组中有一个值,即列表对象。它在其他三个参数传递给get_strategy()后应用,因此传递给request。 Python看到你在调用:

get_strategy("backends", "strategy", "storage", [],
             request="myReq", backend="myBackend", redirect_uri=None, 
             acess_token="myAccToken", id="myId")

并且分别针对backendsstrategystoragerequest参数应用了4个位置参数。

如果您打算传入3个位置参数,请将args指定为空元组:

args = ()

并且工作正常:

>>> def get_strategy(backends, strategy, storage, request=None, backend=None, *args, **kwargs):
...     print request
... 
>>> def load_strategy(*args, **kwargs):
...     get_strategy("backends", "strategy", "storage", *args, **kwargs)
... 
>>> args = ()
>>> kwargs = {"acess_token":"myAccToken", "id":"myId"}
>>> load_strategy(request="myReq", backend="myBackend", redirect_uri=None, *args, **kwargs)
myReq