[Tutor] FrozenDict

Steven D'Aprano steve at pearwood.info
Thu Oct 8 02:47:41 CEST 2015


On Wed, Oct 07, 2015 at 04:10:20PM +0000, 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?

No it doesn't. 

py> fd = FrozenDict(a=1, b=2)
py> fd.keys()
['a', 'b']


That's under Python 2.7.

In 3.3, you will have a problem that FrozenDict is not a proper 
iterator. You can't set self.__next__ = self.next, that won't work. 
Dunder methods have to be on the class, not on the instance, so instead 
of making the assignment in the __init__ method, put this in the body of 
your class:

    def next(self): 
        # Python 2 method
        ...

    __next__ = next  # Python 3 method.


Unfortunately that's not enough to get it working in Python 3. I need 
more time to think about that.


> 2. Is FrozenDict the way to use collections.mapping (aside from the 
> error!). I just discovered this and i seems quite cool (pun intended) 

I think the error is quite significant...


> 3. Which implementation is better, and why? I like ChillyDict better 
> because it is more straightforward and shorter.

I dislike the ChillyDict implementation because it looks like it 
supports item assignment:

hasattr(ChillyDict, '__setitem__') 

will return True, but it actually doesn't. That could make it risky in 
code that assumes that the existence of __setitem__ means you can set 
items.



-- 
Steve


More information about the Tutor mailing list