Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload += in python for a mapping type

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.

like image 499
user1084871 Avatar asked Mar 19 '26 21:03

user1084871


1 Answers

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}
like image 117
DSM Avatar answered Mar 21 '26 10:03

DSM



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!