Dict when defining not returning multi value key error

Chris Angelico rosuav at gmail.com
Fri Aug 1 09:57:57 EDT 2014


On Fri, Aug 1, 2014 at 11:31 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Yes. Although Python promises (at least for classes in the standard
> library) that x == y should imply that hash(x) == hash(y), it says
> nothing about the other way:
>
> x == y implies that hash(x) == hash(y)

This is the entire point of the hashing system. If equal values can
hash differently, why bother calculating the hashes?

Or if you prefer, the point of hashing is the logical converse of the
above: hash(x) != hash(y) implies that x != y. If the hashes are
different, you can skip the equality check, ergo you can build a data
type that claims to search for the key that == the looked-up key, but
actually does a much faster hash check first, and skips everything
with a different hash.

> but hash(x) == hash(y) does NOT imply that x == y.
>

Hello, pigeonhole principle :) If this were false - that is, if equal
hashes DID imply equal objects - it would be necessary to completely
encode an object's state in its hash, and hashes would be impossibly
large. This would, in fact, destroy their value completely.

ChrisA



More information about the Python-list mailing list