I am implementing a class that inherits from UserDict. This class acts completely as expected but I would like to extend its features. I would like it to pass through all methods that have been overriden when acting upon the dictionary. An example would be:
from collections import UserDict
class DummyClass(UserDict):
def __init__(self):
self.mine = {}
self.data = self.mine
def __getitem__(self, key):
print("Doing some stuff here")
return self.data[key]
def __setitem__(self, key, value):
print(f"Uses my __setitem__ {key} {value}")
self.data[key] = value
When doing:
dd = DummyClass()
dd["one"] = {"two": 2}
print(f"First dict: {dd}")
The output is:
Uses my __setitem__ one {'two': 2}
First dict: {'one': {'two': 2}}
However,
dd["one"].update({"two": 4})
print(f"New dict: {dd.keys()}")
will use the modified getitem and use the base method update.
Doing some stuff here
New dict: {'one': {'two': 4}}
What I would like is that dd["one"]
were an object that could be modified calling the modified setitem without having to do dd.update({"one": {"two": 4}})
My question is which is the best way to go about this? In the example above, should I return an object with getitem, modify it and return it? I would like it to be as generic as possible.
It is closely related to question:
Subclassing Python dictionary to override __setitem__
But I was wondering if there is a new approach to this now.
Any help is appreciated