Subclassing Python's dict

Gabriel Genellina gagsl-py2 at
Fri Aug 7 03:29:19 CEST 2009

En Thu, 06 Aug 2009 05:26:22 -0300, Xavier Ho <contact at>
> On Thu, Aug 6, 2009 at 1:19 PM, alex23 <wuwei23 at> wrote:
>> Xavier Ho wrote:
>> > You should subclass collections.UserDict, and not the default dict  
>> class.
>> Xavier, why do you think that is the correct approach?
> I'll be honest first and say that I do not completely understand how  
> dict is
> implemented in the underlying C structure. But as Bruno had already
> mentioned, dict has a slightly different behaviour then we'd expect. For
> example, the __getitem__() function isn't actually used by the  
> interpreter
> (which, you know, *can* be a problem.)

Thinks have evolved...
Before Python 2.2, builtin types were not subclassable. You could not
inherit from dict. In order to write another mapping class, you had to
write the complete interface - or inherit from UserDict, that was a
concrete class implementing the mapping protocol.

Later, DictMixin was added (in 2.3) and it made easier to write other
mapping classes: one had to write the most basic methods (__getitem__ /
__setitem__ / __delitem__ / keys) and the DictMixin provided the remaining
functionality (e.g. values() is built from keys() plus __getitem__). Later
releases allowed an even more modular approach, and until 2.5 DictMixin
was the recommended approach.

Then came 3.0/2.6 and PEP3119 defining a rich hierarchy of abstract base
classes; a normal dictionary implements the MutableMapping ABC and this is
the preferred approach now (the MutableMapping implementation is very
similar to the original DictMixin, but builds on the other base classes
like Sized, Iterable...)

> I didn't realise they took UserDict out in later versions (2.6, for
> example), and put it back in Python 3.0. Does anyone know why?

UserDict still exists on both releases (collections.UserDict on 3.x), but
it's not the preferred approach to implement a new mapping class anymore.

Gabriel Genellina

More information about the Python-list mailing list