5
votes

I'm trying to get my head around **kwargs in python 3 and am running into a strange error. Based on this post on the matter, I tried to create my own version to confirm it worked for me.

table = {'Bob':'Old','Franny':'Less Old, Still a little old though','Ribbit':'Only slightly old'}

def kw(**kwargs):
    for i,j in kwargs.items():
        print(i,'is ',j)

kw(table)

The strange thing is that I keep getting back TypeError: kw() takes 0 positional arguments but 1 was given. I have no idea why and can see no appreciable difference between my code and the code in the example at the provided link.

Can someone help me determine what is causing this error?

3

3 Answers

13
votes

call kw function with kw(**table)

Python 3 Doc: link

2
votes

There's no need to make kwargs a variable keyword argument here. By specifying kwargs with ** you are defining the function with a variable number of keyword arguments but no positional argument, hence the error you're seeing.

Instead, simply define your kw function with:

def kw(kwargs):
0
votes

Writing a separate answer because I do not have enough reputation to comment.

There is another error in the original post, this time in the function definition

Once you have "opened" a dict with the ** operator in arguments, the dict does not exist any more inside the function. So in the function:

def kw(**kwargs):
    for i,j in kwargs.items():
        print(i,'is ',j) 

the local variables will be Bob, Franny and Ribbit, with their respective values