[Tutor] Understanding the error "method got multiple values for keyword argument "

Steven D'Aprano steve at pearwood.info
Wed Mar 1 06:29:39 EST 2017


On Wed, Mar 01, 2017 at 01:48:04PM +0530, Pabitra Pati wrote:
> I want to understand the error message I am getting.
> Below is my code piece :-
> 
>     def total(name, *args):
>         if args:
>             print("%s has total money of Rs %d/- " %(name, sum(args)))
>         else:
>             print("%s's piggy bank  has no money" %name)

We can simplify the code by just ignoring the body :-)

def total(name, *args):
    pass


> I can call this method passing the extra arguments inside *().
> *I know the correct way of passing the arguments.* But, I am passing value
> for 'name' in form of param=value, *intentionally*, so that it throws me
> error. However, I am unable to understand the below error message :-
[...]
>     TypeError: total() got multiple values for keyword argument 'name'

The rules for how function arguments are assigned to parameters are 
given here:

https://docs.python.org/3/reference/expressions.html#calls


The documentation even includes an example similar to yours.

Basically, if I am reading it correctly, Python starts by building a 
sequence of empty slots, one for each named parameter:

    name = <blank>

plus a slot for any extra arguments. Those slots are filled in using 
positional arguments, including starred expressions, *then* keyword 
arguments are assigned, so in your example you get the `name` parameter 
filled in twice: once as a positional argument, and the second time as 
the keyword argument.



-- 
Steve


More information about the Tutor mailing list