Dictionary from list?

Greg Chapman glchapman at earthlink.net
Mon Oct 29 14:35:06 EST 2001


On Mon, 29 Oct 2001 02:58:42 -0500, Guido van Rossum <guido at python.org> wrote:

>
>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.
>

In fact I have a UserDict-like class which implements the behavior I want, and
which I will continue to use.  Given the new subclasses, it seemed logical to
try to convert this class into a dictionary subclass, since the intent is for it
to work identically to a dictionary except that it has the additonal property
that the order of iteration is defined.  My thinking was that as a subclass, I
could use it in situation (a), where a genuine dictionary is required.  However,
I see now that this class is not a subclass of dictionary (since it breaks
fundamental aspects of its purported superclass), but an implementation of a
subtype of the mapping type implemented by dictionary.  So the class can use a
dictionary as part of its implementation, but it is not itself a dictionary.

I agree that it would be very helpful to have some documentation of what parts
of the built-in types should be considered fundamental.

By the way, in thinking about situation (a), I was wondering how much of a
slow-down would be involved if PyDict_XXX calls were changed to PyMapping_XXX
(I'm not advocating that, I was just curious).  Anyway, while doing so, I
happened to notice the following two macros in abstract.h:

#define PyMapping_DelItemString(O,K) PyDict_DelItemString((O),(K))
#define PyMapping_DelItem(O,K) PyDict_DelItem((O),(K))

I assume those are oversights?  It seems to me they should delegate to
PyObject_DelItem (and PyObject_DelItemString, which will have to be added).

Anyway, thanks for your reply, and thanks for Python!

---
Greg Chapman




More information about the Python-list mailing list