I'd like to use a += notation for updating a dict-like object in Python. I want to have the same behavior as dict.update method. Here is my class (dictionary with "." access):
class sdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
I tried:
__iadd__ = dict.update
And:
def __iadd__(self, other):
self.update(other)
return self
but none of these work. (the first destroys the original dictionary and the second generates SyntaxError)
Update:
Second definition actually works. It didn't work for me because I forgot def. The first one doesn't work because dict.update returns None.
I think all you're missing is a def:
class sdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
def __iadd__(self, other):
self.update(other)
return self
>>> a = sdict()
>>> a.b = 3
>>> a
{'b': 3}
>>> a.b
3
>>> a['b']
3
>>> a += {'fred': 3}
>>> a
{'b': 3, 'fred': 3}
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