Usually, I can willy-nilly monkey-patch and mock methods:
from UserDict import DictMixin
class py2fake_dict(DictMixin):
def __setitem__(self, name, value):
raise AssertionError("Don't talk to me!")
def __delitem__(self, name):
pass
def __getitem__(self, name):
pass
def __iter__(self):
yield None
def __len__(self):
return 0
c = py2fake_dict()
c.__setitem__ = lambda name, value: 'All clear.'
# This is OK:
c[1] = 2
However, if the method in question is on a MutableMapping subclass, I cannot:
from collections import MutableMapping
class py3fake_dict(MutableMapping):
def __setitem__(self, name, value):
raise AssertionError("Don't talk to me!")
def __delitem__(self, name):
pass
def __getitem__(self, name):
pass
def __iter__(self):
yield None
def __len__(self):
return 0
c = py3fake_dict()
c.__setitem__ = lambda name, value: 'All clear.'
# This hits the assertion!!!
c[1] = 2
I found this in working code when upgrading from UserDict.DictMixin to collections.MutableMapping as part of our Python3 upgrade. I'll remove the code, or use subclass in the future, but I just want to understand what is happening.