"got multiple values for keyword argument" when using *args, **kwargs in a python function

StackOverflow https://stackoverflow.com/questions/20600870

Вопрос

When passing a named parameter request through **kwargs, I get an error-

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'

The code in testKwargs.py is below-

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)

I was expecting that there would be one key-value pair for the key request in the **kwargs of load_strategy which was passed on to the request parameter in get_stragegy, but that doesn't seem to be the case.

I am trying to figure out what I am missing here.

Это было полезно?

Решение

You are passing in an extra positional argument:

args = ([],)

There is one value in that tuple, a list object. It is applied after the other three arguments passed to get_strategy(), so to request. Python sees you calling:

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

and the 4 positional arguments are applied against the backends, strategy, storage and request parameters respectively.

If you meant to pass in 3 positional arguments, then specify args as an empty tuple:

args = ()

and things work just fine:

>>> 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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top