The goal is to somehow automatically compute the values for 'dead' and 'alive' when the values of the dict are being accessed.

However, it is not simply possible to implement a check for access to some kind of values attribute within __getattribute__ , because dict is a (C-based) python built-in and does not have an attribute like that. Additionally, special method lookup bypasses __getattribute__ because of speed optimisations.

Unfortunately, there is no exposed common method for the methods of dict to access values ( values , items only return views, everything is handled internally), so that it is necessary for all these methods to explicitly update beforehand.

One solution would be to override every such function in the style of

def accessing_method(self): self._update_dead_and_alive() return super().accessing_method()

The other would be programmatically

from functools import wraps cats = [] def add_state_update(cls): # all the methods accessing values of dict accmethods_names = [ '__repr__', '__getitem__', 'get', 'items', 'pop', 'popitem', 'setdefault', 'values' ] def state_update(method): def update_dead_and_alive(self): self['dead'] = cats.count('dead') self['alive'] = cats.count('alive') @wraps(method) def wrapper(*args, **kwargs): update_dead_and_alive(*args) return method(*args, **kwargs) return wrapper # put update_dead_and_alive in front of the execution of every # accmethod for n in accmethods_names: method = getattr(cls, n) setattr(cls, n, state_update(method)) return cls @add_state_update class SchrodingersDict(dict): pass box = SchrodingersDict([('dead', 0), ('alive', 0)])

Which gives the following results when tested against the mentioned functions

>>> cats.append('alive') >>> cats.append('dead') >>> cats.append('dead') >>> >>> import pickle >>> pickle.loads(pickle.dumps(box)) {'dead': 2, 'alive': 1} >>> >>> cats.append('alive') >>> import json >>> json.loads(json.dumps(box)) {'dead': 2, 'alive': 2} >>> >>> cats.append('alive') >>> eval(repr(box)) == box True

The first version leads to a similiar amount of code and is more explicit, probably.