Question: How can I Intercept __getitem__
calls on an object attribute?
Explanation:
So, the scenario is the following. I have an object that stores a dict-like object as an attribute. Every time the __getitem__
method of this attribute gets called, I want to intercept that call and do some special processing on the fetched item depending on the key. What I want would look something like this:
class Test:
def __init__(self):
self._d = {'a': 1, 'b': 2}
@property
def d(self, key):
val = self._d[key]
if key == 'a':
val += 2
return val
t = Test()
assert(t.d['a'] == 3) # Should not throw AssertionError
The problem is that the @property method doesn't actually have access to the key in the __getitem__
call, so I can't check for it at all to do my special postprocessing step.
Important Note: I can't just subclass a MutableMapping, override the __getitem__
method of my subclass to do this special processing, and store an instance of the subclass in self._d
. In my actual code self._d
is already a subclass of MutableMapping and other clients of this subclass need access to the unmodified data.
Thanks for any and all help!