Ian Kelly ian.g.kelly at
Thu Feb 9 03:13:10 CET 2012

On Wed, Feb 8, 2012 at 6:23 PM, Evan Driscoll <edriscoll at> wrote:
> Hi all,
> I've been trying for a few days (only a little bit at a time) to come up
> with a way of implementing a frozendict that doesn't suck. I'm gradually
> converging to a solution, but I can't help but think that there's some
> subtlety that I'm probably missing which is why it's not already provided.
> Does anyone know why Python doesn't already come with a frozendict, or
> why there seem to only be a couple attempts to write one?

Define "doesn't suck".  If I were to hack one up, it would look
something like this:

from collections import Mapping, Hashable

class frozendict(Mapping, Hashable):

    def __init__(self, *args, **kwargs):
        self.__dict = dict(*args, **kwargs)

    def __len__(self):
        return len(self.__dict)

    def __iter__(self):
        return iter(self.__dict)

    def __getitem__(self, key):
        return self.__dict[key]

    def __hash__(self):
        return hash(frozenset(self.__dict.iteritems()))

    def __repr__(self):
        return 'frozendict(%r)' % (self.__dict,)

Not extensively tested, but it seems to work pretty well for me.


More information about the Python-list mailing list