On 10/08/2010 02:23 AM, kj wrote:
I imagine that frozenset is better than sorted(tuple(...)) here,
but it's not obvious to me why.
dicts are unsorted. That means their item-order is undefined. So are sets.
If you want a hash that is independent from the order of items, you
could ensure the items are always in the same order when you do the
hashing; or you could use a hashing algorithm that ignore item order.
As creating a `frozenset` is probably more efficient than sorting, that
is the preferred solution.
Here's my implementation suggestion:
class frozendict(dict):
def _immutable_error(self, *args, **kwargs):
raise TypeError("%r object is immutable" % self.__class__.__name__)
__setitem__ = __delitem__ = clear = pop \
= popitem = setdefault = update = _immutable_error
def __hash__(self):
return hash(frozenset(self.iteritems()))
Only 9 lines :-)
Jonas
--
http://mail.python.org/mailman/listinfo/python-list