project_ananthu project_ananthu - 1 year ago 86
Python Question

Why does this code using variable arguments give a TypeError?

Why am i getting this an error in this code?

def fun(a,*b):

when the code is executed I get this error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fun() got an unexpected keyword argument 'x'

Answer Source

Your function doesn't take keyword arguments at all, only positional arguments. The *varargs syntax only captures extra positional arguments (without a name= prefix).

Either drop the keyword argument syntax and pass in positional arguments only, or update your function to take keyword arguments too.

The following works:

fun(1, 4, 5)  # b will be set to (4, 5)

or add **c or a similar keyword **varkwargs name to the function signature:

def fun(a, *b, **c):
    print(a, b, c)

fun(1, x=4, y=5)  # prints 1 () {'x': 4, 'y': 5}

For this specific example, the *b argument could be dropped since you don't actually pass in more than one positional argument here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download