Hashability?

Dan Bishop danb_83 at yahoo.com
Mon Jul 19 02:28:51 EDT 2004


"Chris S." <chrisks at NOSPAMudel.edu> wrote in message news:<cdfd0p$ls9$1 at scrotar.nss.udel.edu>...
> Perhaps this is obvious to some, but why are dictionary keys constrained 
> to hashable objects?

Because dictionaries are implemented as hash tables.  But that's not
helpful, because your real question is "Why were lists and
dictionaries made unhashable?"

Well, what do you expect their hash value to be?  It can't be based on
their contents, because those can change.  It can't be based on object
ID, either, because different (in id) lists can be equal (in
contents), and that violates the principle that x == y implies hash(x)
== hash(y).

I suppose the hash code of a mutable type could be defined as always
zero, which would be consistent, but horrible in terms of efficiency.

So the only reasonable thing to do is make these types non-hashable.

> why not use the object's id for the hash value.

That *is* done by default.

>>> x = object()
>>> hash(x)
1075889080
>>> id(x)
1075889080
>>> {x: 0}
{<object object at 0x4020c3b8>: 0}

This is acceptable because the default implementation of the "=="
operator is the same as the "is" operator, so x == y implies id(x) ==
id(y) implies hash(x) == hash(y), so it's a consistent hash function.



More information about the Python-list mailing list