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?
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.
**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.
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.
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.
call kw function with kw(**table)
Python 3 Doc: link
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With