Someone cannot create an instance of your SpecialDict
as a dictionary, because that is the dictionary literal; normal dictionary.
As for setting elements with a quadratic note, as in mySpecialDict['hello'] = 54
, this only mySpecialDict.__setitem__('hello', 54)
. Similarly, getting an element with a square bracket corresponds to calling the __getitem__
method. This is true no matter which class mySpecialDict
; be it a regular dictionary, a class that subclasses an inline dict
or some completely unrelated class. Therefore, you can simply implement these methods to change what they do (using super(SpecialDict, self).__setitem__(key, value)
or dict.__setitem__(self, key, value)
to refer to the normal implementation when you necessary).
One problem you will encounter is that some (all?) __getitem__
implementations of other dict methods will not respect your overridden __setitem__
or __getitem__
. Therefore, you cannot inherit them; you will have to redefine all of them and either completely repeat them in terms of your versions of the basic operations, or at least perform your checks around the superclass calls.
A less painful approach might be to not subclass the inline dict and instead implement its own "dict-like" object, which wraps a regular dictionary using the base classes collections.Mapping
or collections.MutableMapping
to get a dictionary interface. Using this approach, you only need to implement about 6 basic methods (what you would do by including the verification logic around calls in a wrapped dictionary) and get reasonable definitions of other methods based on them. See http://docs.python.org/library/collections.html#collections-abstract-base-classes
source share