Subclassing Python's dict

Xavier Ho contact at xavierho.com
Thu Aug 6 04:26:22 EDT 2009


On Thu, Aug 6, 2009 at 1:19 PM, alex23 <wuwei23 at gmail.com> wrote:

> Xavier Ho wrote:
> > You should subclass collections.UserDict, and not the default dict class.
> > Refer to the collections module.
>
> 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.)

http://www.python.org/download/releases/2.2.3/descrintro/#subclassing
(I don't know if 2.6.2 changed anything since 2.2.3, but there are some
references you can look at, and sample code.)

To answer your question, it's really not "the correct approach", but I think
(meaning: untested) UserDict doesn't have the same implementation, which
might free up some restrictions Sergey encountered.

The docs say
> "The need for this class has been largely supplanted by the ability to
> subclass directly from dict (a feature that became available starting
> with Python version 2.2)."


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?

So, I do not actually know.

> If you mean that Sergey should subclass _in this instance_ could you
> please explain why? (Sorry if you already have, I never saw your
> original post...)
>

It was really more or less an educated guess. He didn't tell us what he is
trying to achieve, so _in this instance_ I can't give more advice than
saying "well, if this doesn't work, here are you other options that I know
of/just found. Try these and let us know if you got it to work." *winks*

-

Sometimes I do answer a little too quickly, I apologise for that.

- Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090806/bade6952/attachment.html>


More information about the Python-list mailing list