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?
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'})