keety
keety

Reputation: 17461

What are the rules for mixing keyword argument and * tuple in python function call

I'm having difficulty understanding the rules for mixing keyword arguments and *tuple in a python function call

More specifically with the regard to the below code snippet

def  func(a,b,c):
    print("These are the arguments",a,b,c)

args = [2]
#Case 1: expected output "These are the arguments:1,2,3" works fine
func(1,c=3,*args)

#Case 2:expected output "These are the arguments:1,3,2" raises TypeError
func(1,b=3,*args)

I wanted to understand why case 1 works but case 2 raises a TypeError: func() got multiple values for argument 'b'

It looks to me as per the language reference doc the above form of mixing of keyword argument and *tuple is valid. Sorry if i'm missing something obvious.

Tested on 3.4 and 2.7.6.

Upvotes: 2

Views: 535

Answers (1)

StenSoft
StenSoft

Reputation: 9617

Keyword arguments are not counted when evaluating positional arguments, so in the latter case, you try to provide b twice, once with keyword arguments and once with positional arguments. The following method calls are equivalent:

func(1, b=3, *args)
func(1, *args, b=3)

By the way, a very similar example is shown in the linked documentation just under the frame with CPython implementation details.

Upvotes: 3

Related Questions