dictionary mutability, hashability, __eq__, __hash__

Ned Batchelder ned at nedbatchelder.com
Sun Nov 27 10:50:14 EST 2016


On Sunday, November 27, 2016 at 4:53:20 AM UTC-5, Veek M wrote:
> I was reading this: http://stackoverflow.com/questions/4418741/im-able-to-use-a-mutable-object-as-a-dictionary-key-in-python-is-this-not-disa
> 
> In a User Defined Type, one can provide __hash__ that returns a integer 
> as a key to a dictionary.

This is not correct: the value returned by __hash__ is not the key.  The
object is the key, and the dictionary uses the hash value internally. It
also uses equality comparison.

There are two rules for using an object as a key in a dictionary:

1) The things an object is equal to must not change over the lifetime
of the object.

2) If two objects compare equal (with ==, that is to say, with __eq__),
then they must have equal __hash__ values.

Dictionaries consider two values the same key if they compare equal with
__eq__.  The __hash__ value is used as a critical optimization, which is
why these two rules must hold.

Rule 1 is hard to express succinctly, but it means that whatever
characteristics of the object are included in the equality
comparison, those characteristics must not change.  Immutable objects,
with no changeable characteristics at all, manage this easily.

--Ned.



More information about the Python-list mailing list