Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this unexpected keyword argument TypeError?

I'm testing some code with *args and **kwargs, and I wrote a dictionary for the **kwargs. For some reason, I'm getting

def func(*args, **kwargs):
    if args:
        second_test(*args)
    elif kwargs:
        second_test(**kwargs)

def second_test(stringa, integera, floata):
    print("Name: %s, Problems Correct: %d, Points: %f" % (stringa, integera, floata))

profile_1 = ["David", 21, 132.00]
func(*profile_1)

profile_1a = {'Name': 'David', 'Problems Correct': 21, 'Points': 132.00}
func(**profile_1a)

The code starts from line 44 and ends at line 57. This is the error I'm getting:

TypeError: second_test() got an unexpected keyword argument 'Name'

I've googled "unexpected keyword argument", but I can never find a definition; only other stackoverflow articles. What is wrong with my code?

like image 788
mpnm Avatar asked Aug 15 '19 06:08

mpnm


2 Answers

When passing kwargs into a function, it expects to find the exact variable name in the list. If instead your dictionary keys were stringa, integera, and floata the function would work without problem.

So you either need to change your function variable names or change the key names in your dictionary to get this to work

like image 174
Novice Avatar answered Oct 25 '22 07:10

Novice


keyword argument is all of the "unknown/unexpected" named argument that being passed by name.

for example, let's define a function with one argument

def func(a):
    print(a)

now, if we call this function with an "unexpected" named argument like so

func(b=3) # remember we didn't define b as an argument

then we will get a TypeError. However, if we modify the function to accept these "unexpected" named arguments, then we can run the previous code

def func(a, **kwargs):
    print(a)
    print(kwargs["b"]) # now, if we pass an argument 'b' to the function, this will print its value (if we don't, we get a KeyError)

> func(3, b=15)
3
15

like image 37
בנימין כהן Avatar answered Oct 25 '22 06:10

בנימין כהן