sublcassing dict without losing functionality

Steve Holden steve at
Mon Nov 1 22:29:44 CET 2004

Mathias Waack wrote:

> Steven Bethard wrote:
>>I'd like to subclass dict to disallow overwriting of keys,
>>something like:
> <snip>
>>The problem is, dict doesn't appear to call __setitem__ in any of
>>the __init__ forms, so none of the following raise errors as I'd
>>like them to:
> <snap>
>>etc.  Is there a simple way to override this behavior in dict
>>having to rewrite __init__?  There are so many cases in
>>dict.__init__ that I'm hesitant to try to reproduce them all...
> How about starting with UserDict (source comes with your python
> distribution) and modifying it for your needs?

Well, here's one reason I can think of:

 >>> from UserDict import UserDict
 >>> issubclass(UserDict, object)
 >>> issubclass(dict, object)
 >>> d = UserDict()
 >>> type(d)
<type 'instance'>

UserDict is an old-style class. Simply converting it to use object as a 
metaclass won't get you anywhere near the speed of a true dict.

Holden Web LLC +1 800 494 3119

More information about the Python-list mailing list