Subclassing dict to modify values

Matt Wheeler m at funkyhat.org
Wed Aug 2 20:02:29 EDT 2017


On Wed, 2 Aug 2017 at 23:26 Ian Pilcher <arequipeno at gmail.com> wrote:

> YANQ (Yet Another Newbie Question) ...
>
> I would like to create a subclass of dict that modifies values as they
> are inserted.  (Effectively I want to do the equivalent of "interning"
> the values, although they aren't strings.)
>
> Do I need to implement any methods other than __setitem__?  (I.e. will
> any other methods/operators that add values to the dictionary call my
> __setitem__ method?)
>

Yes. At least update and setdefault will also need to be overridden.

You will probably be better off creating a class which inherits from
collections.MutableMapping .

A MutableMapping subclass behaves like a dict (i.e. is a mapping type) as
long as the minimum required methods are defined. See the table for the
required methods at
https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes

All of the mixin methods (the ones defined for you) will call the abstract
methods you override.
-- 

--
Matt Wheeler
http://funkyh.at



More information about the Python-list mailing list