frozendict (v0.1)

kj no.email at please.post
Fri Oct 8 02:23:30 CEST 2010


In <87hbgxlk67.fsf at gmail.com> Arnaud Delobelle <arnodel at gmail.com> writes:

>A simple fix is to use hash(frozenset(self.items())) instead.

Thanks for pointing out the hash bug.  It was an oversight: I meant
to write

    def __hash__(self):
        return hash(sorted(tuple(self.items())))

I imagine that frozenset is better than sorted(tuple(...)) here,
but it's not obvious to me why.

At any rate, using your suggestions in this and your other post,
the current implementation of frozendict stands at:

class frozendict(dict):
    for method in ('__delitem__ __setitem__ clear pop popitem setdefault '
                   'update').split():
        exec """
def %s(self, *a, **k):
    cn = self.__class__.__name__
    raise TypeError("'%%s' object is not mutable" %% cn)
""" % method

    def __hash__(self):
        return hash(frozenset(self.items()))

...which is a lot nicer!

Thanks!

~kj



More information about the Python-list mailing list