Search code examples
pythontypesdictionarycustomizationinternals

How to change the behavior of a python dictionary's __setattr__?


In Python, everything has a class. Therefore dict also has a class.

So, in theory, I should be able to change the implementation of the keyvalue assignment behavior.


Example:

d = dict()
d['first'] = 3    # Internally d['first'] is stored as 6 [i.e. value*2 if value is INT]

print d['first']  # should print 6

d['second'] = 4 

print d['second'] # should print 8


I noticed that most objects have attributes listed in OBJECT.__dict__ or vars(OBJECT). But this isn’t the case for dict or list.

How can I get the desired behavior by overriding dict.__setattr__() method?


Solution

  • It is __setitem__ that have to be overriden in this case - and it is as simples as:

    class MyDict(dict):
        def __setitem__(self, key, value):
             dict.__setitem__(self, key, 2 * value)
    

    Example:

    >>> m  = MyDict()
    >>> m[0] = 5
    >>> m
    {0: 10}
    

    __setattr__ controls how object attributes themselves (not key/value pairs) are attributed.