---------------------------------------- > Date: Thu, 8 Oct 2015 11:47:41 +1100 > From: st...@pearwood.info > To: tutor@python.org > Subject: Re: [Tutor] FrozenDict > > 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__')
Thanks. I had not considered that. I usually use try-except (forgiveness) rather than hasattr (permission) I will post another implementation shortly. > > 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 > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor