[Tutor] FrozenDict

Albert-Jan Roskam sjeik_appie at hotmail.com
Sat Oct 10 13:28:05 CEST 2015


----------------------------------------
> From: alex at alexchabot.net
> To: tutor at python.org
> Date: Wed, 7 Oct 2015 18:54:42 +0200
> Subject: Re: [Tutor] FrozenDict
>
> Hi Albert-Jan,
> As far as I know, the recommended object to subclass when subclassing a `dict` is `UserDict`. In Python 3, it's in `collections.UserDict` and in Python 2 is in `UserDict.UserDict`.
>
> Here's an basic example of how it would work:
>
> try:
> from collections import UserDict
> except ImportError:
> from UserDict import UserDict
>
> class FrozenDict(UserDict):
> def __setitem__(self, key, item):
> raise TypeError("'FrozenDict' object does not support item assignment")
>
> According to the Fluent Python book (by Luciano Ramalho, which I recommend wholeheartedly), subclassing built-in types is tricky because: "the code of the built-ins (written in C) does not call special methods overridden by user-defined classes." Therefore, other methods of `dict`, like `update` or `__init__` will *not* call your special `__setitem__` method.
>
> However, be aware that although the FrozenDict above is read-only, it's not *really* frozen, i.e., it cannot be used as a key in another dict. In order to do that, you would need to define the `__hash__` method.
>
> This StackOverflow answer, which you might have seen, provide an implementation of a FrozenDict that could be used as a dict.
> http://stackoverflow.com/questions/2703599/what-would-a-frozen-dict-be
>
> Cheers,
> Alex
>

Aha, that's useful to know. So it's a no-no to subclass *any* builtin?

I checked collections.UserDict and it indeed looks promising. Caveat: it;s Python 3 only (not sure what versionit was introduced).

Best wishes,
Albert-Jan
 		 	   		  


More information about the Tutor mailing list