Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

**Kwargs 0 positional arguments Error

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 = {'Person A':'Age A','Person B':'Age B','Person C':'Age C'}

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?

like image 877
Jwok Avatar asked Jul 18 '18 07:07

Jwok


People also ask

What does zero positional arguments but one is given mean?

The Python "TypeError: takes 0 positional arguments but 1 was given" occurs for multiple reasons: Forgetting to specify the self argument in a class method. Forgetting to specify an argument in a function. Passing an argument to a function that doesn't take any arguments. Overriding a built-in function by mistake.

Can Kwargs be empty?

**kwargs allow a function to take any number of keyword arguments. By default, **kwargs is an empty dictionary. Each undefined keyword argument is stored as a key-value pair in the **kwargs dictionary.

What is positional arguments in Python with example?

Positional arguments are simply an ordered list of inputs in a Python function call that correspond to the order of the parameters defined in the function header. In this example, we have defined a the function func with parameters num1 , and num2 . When calling the function, the argument order matters.

What is a positional argument?

Positional arguments are arguments that need to be included in the proper position or order. The first positional argument always needs to be listed first when the function is called. The second positional argument needs to be listed second and the third positional argument listed third, etc.


2 Answers

call kw function with kw(**table)

Python 3 Doc: link

like image 59
richard_ma Avatar answered Nov 15 '22 12:11

richard_ma


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):
like image 44
blhsing Avatar answered Nov 15 '22 10:11

blhsing