[Tutor] FrozenDict

Alexandre Chabot-Leclerc alex at alexchabot.net
Wed Oct 7 18:54:42 CEST 2015


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

On Wed, Oct 7, 2015, at 18:10, Albert-Jan Roskam wrote:
> Hi,
> I wanted to create a read-only dict to hold some constants. I looked around on the internet and created two implementations:-FrozenDict (derives from collections.mapping)-ChillyDict (derives from dict, which seems more obvious to me)
> The code can be found here: http://pastebin.com/QJ3V2mSK
> Some questions:1. one doctest from FrozenDict fails: fd.keys() returns an empty list. Why?2. Is FrozenDict the way to use collections.mapping (aside from the error!). I just discovered this and i seems quite cool (pun intended)3. Which implementation is better, and why? I like ChillyDict better because it is more straightforward and shorter.
> The read-only dict does not need to be very fast, it just needs to give some reasonable protection against mutating values.It also needs to work under Python 2.7 and 3.3+.
> Thank you!
> Albert-Jan
> 
> 
>  		 	   		  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list