Is there a way of subclassing from dict and collections.abc.MutableMapping together? Is there a way of subclassing from dict and collections.abc.MutableMapping together? python-3.x python-3.x

Is there a way of subclassing from dict and collections.abc.MutableMapping together?


What you could do:

This likely won't work out well (i.e. not the cleanest design), but you could inherit from MutableMapping first and then from dict second.

Then MutableMapping would use whatever methods you've implemented (because they are the first in the lookup chain):

>>> class D(MutableMapping, dict):        def __getitem__(self, key):            print(f'Intercepted a lookup for {key!r}')            return dict.__getitem__(self, key)>>> d = D(x=10, y=20)>>> d.get('x', 0)Intercepted a lookup for 'x'10>>> d.get('z', 0)Intercepted a lookup for 'z'0

Better way:

The cleanest approach (easy to understand and test) is to just inherit from MutableMapping and then implement the required methods using a regular dict as the base data store (with composition rather than inheritance):

>>> class CapitalizingDict(MutableMapping):        def __init__(self, *args, **kwds):            self.store = {}            self.update(*args, **kwds)        def __getitem__(self, key):            key = key.capitalize()            return self.store[key]        def __setitem__(self, key, value):            key = key.capitalize()            self.store[key] = value        def __delitem__(self, key):            del self.store[key]        def __len__(self):            return len(self.store)        def __iter__(self):            return iter(self.store)        def __repr__(self):            return repr(self.store)>>> d = CapitalizingDict(x=10, y=20)>>> d{'X': 10, 'Y': 20}>>> d['x']10>>> d.get('x', 0)10>>> d.get('z', 0)0>>> d['w'] = 30>>> d['W']30


matomo