Is there a way to insert hooks into a native dictionary type to see when a query arrives and what's looked up?

Chris Angelico rosuav at
Wed Dec 14 01:29:47 EST 2016

On Wed, Dec 14, 2016 at 5:11 PM, Veek M <vek.m1234 at> wrote:
> I know that with user classes one can define getattr, setattr to handle
> dictionary lookup. Is there a way to hook into the native dict() type
> and see in real time what's being queried.
> I wanted to check if when one does:
> x.sin()
> if the x.__dict__ was queried or if the Foo.__dict__ was queried.. I
> know method/attribute lookup starts with the instance but was wondering
> if I could see it in action vs defining __getattr__ __setattr__ in Foo
> which is a bit indirect.. and not what I want.

Normally, I would say "subclass dict and override __getitem__", but
interestingly, that doesn't seem to work. You can put a subclass of
dict in an object's __dict__, but Python won't call your functions -
at least, CPython 3.7 won't. Presumably the actual lookups and updates
are done by directly tinkering with the dict's internals, from C.


More information about the Python-list mailing list