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

Peter Otten __peter__ at web.de
Wed Mar 1 05:50:10 EST 2017


Alan Gauld via Tutor wrote:

> On 01/03/17 08:18, Pabitra Pati wrote:
> 
>>     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)
>> 
>> 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 you expected to get an error?
> So what exactly are you asking about? Which error did
> you think you would get?
> 
> Remember that you are not allowed to pass positional
> arguments after you pass a named argument. So python
> sees your call as something like:
> 
> total(name = "John", 1, 2, 10 )

I think total(name="John", *(1, 2, 3))

is rather resolved as

total(1, 2, 3, name="John")

so that the first argument is both 1 and "John". I conclude that from
 
>>> def total(name, other):
...     print("name:", name, "other:", other)
... 
>>> total(other=42, "John")
  File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>> total(other=42, *["John"])
('name:', 'John', 'other:', 42)

But this is tricky, and I usually resort to trial-and-error when I run into 
such problems.


> ie as 4 arguments being passed to name and
> *args and can't figure out where name stops and
> *args begins. It could be any of:
> 
> total( name=("John", 1),  2, 10 ) or
> total( name=("John", 1, 2),  10 ) or
> total( name=("John", 1, 2, 10)  )  # empty *args is allowed.
> 
> The whole point of *args is that they represent unnamed
> arguments, you may not put named arguments in front of
> them, it's illegal.
> 
>> However, I am unable to understand the below error message :-
>> 
>>     >>> total(name="John", *(1, 2, 10) )
>>     Traceback (most recent call last):
>>       File "<stdin>", line 1, in <module>
>>     TypeError: total() got multiple values for keyword argument 'name'
>> 
>> How Python is evaluating the above call, that it's getting multiple
>> values
>> for the parameter 'name'?  How the call is being interpreted internally?
> 
> If you want the technical details of how the interpreter
> is working there are others better qualified to explain,
> but since what you are trying to do is not valid Python
> I'm not sure there is much point in analyzing it.
> 




More information about the Tutor mailing list