Dictionary from list?

Guido van Rossum guido at python.org
Mon Oct 29 08:58:42 CET 2001

Subclassing list and dictionary etc. should be seen as an experimental
feature; I don't want to fully fix the semantics yet in all cases.

I think of these types as having two sets of interfaces: an internal,
fixed one (e.g. PyDict_SetItem) and an external, overridable one
(e.g. __setitem__).  The external operations are defined in terms of
the internal ones.  When you invoke an operation with a Python
notation (e.g. dict[key]), you invoke the external operation, and
hence overrides will have the expected effect.  But many accesses from
inside the Python VM (e.g. dictionary use by exec) and from other
methods (e.g. dict.update) invoke the internal versions of various
operations, and hence won't see the overrides.

IMO, fixing these internal accesses to always use the overrides would
remove much of the attractiveness of subclassing built-in types; I
believe it would slow things down too much given the current state of
the implementation.

If you want a vaguely dictionary-like object, write a class that
doesn't derive from dictionary but implements the mapping protocol; if
you want a base class that implements most of the operations already,
start with UserDict.

Subclassing a built-in type is appropriate when either (a) you want to
use it in a context where a genuine list/dictionary/file/etc.; or (b)
you want the speed advantage of the built-in type.  In both cases you
have to live with some restrictions.  Remapping the fundamental
accessors (like __getitem__) is probably not a good idea in either
case.  Adding new state and behavior is fine.

We should document this more clearly and in more detail.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-list mailing list