sublcassing dict without losing functionality
Steve Holden
steve at holdenweb.com
Mon Nov 1 16:29:44 EST 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
>>without
>>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)
0
>>> issubclass(dict, object)
1
>>> 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.
regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
More information about the Python-list
mailing list