Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python method takes one positional argument but two were given [duplicate]

I came across an error which I don't quite understand. If I have the following snippet:

class Test(object):
  def __init__(self):
    self.data = {}

  def update_data(self, **update):
    self.data = update

t = Test()

t.update_data(test='data') #  Works
t.update_data({'test':'data'}) #  TypeError: update_data() takes 1 positional argument but 2 were given

So from what I understand, the **update syntax is the dictionary destructing syntax and when you pass a dict to the function, it gets converted into keyword arguments.

What am I understanding improperly here?

like image 550
Bhargav Avatar asked May 05 '26 00:05

Bhargav


1 Answers

If you just pass in a dictionary it will be treated as any other variable. In your case you passed it in as positional argument so it will be treated as positional argument. The method, however, doesn't accept any positional arguments (except self but that's another story) so it throws an error.

If you want to pass the dictionary contents as keyword arguments you need to unpack it (** in front of the dictionary):

t.update_data(**{'test':'data'})

If you want to pass in a dictionary as dictionary you can also pass it in as keyword argument (no unpacking is done then!):

t.update_data(funkw={'test':'data'})
like image 128
MSeifert Avatar answered May 07 '26 14:05

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!