Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'got multiple values for argument' error for *args and **kwargs?

Consider the following:

def my_wrapper(wrapper_argument=False, *args, **kwargs):
  return my_function(*args, **kwargs)

def my_function(arg1, arg2, params=None):
  # do_stuff
  return result

when I call the above with:

my_wrapper('foo', 'bar', wrapper_argument=True)

I get:

TypeError: my_function() got multiple values for argument 'wrapper_argument'

Why? Is the ordering of the arguments perhaps wrong?

like image 329
Amelio Vazquez-Reina Avatar asked Dec 25 '22 23:12

Amelio Vazquez-Reina


2 Answers

You are assigning foo to wrapper_argument (because its the first positional argument); then you are assigning it again as an optional keyword argument.

When you pass these arguments from your wrapper to the callable, Python pops the error.

To avoid it, don't pass in an optional keyword argument similar to an existing keyword argument.

like image 61
Burhan Khalid Avatar answered Apr 27 '23 23:04

Burhan Khalid


Since the question is for Python 3, you can re-order the arguments in the function definition as follows:

Instead of:

def my_wrapper(wrapper_argument=False, *args, **kwargs):

do:

def my_wrapper(*args, wrapper_argument=False, **kwargs):

and keep everything else the same.

like image 28
Amelio Vazquez-Reina Avatar answered Apr 27 '23 23:04

Amelio Vazquez-Reina