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. -- https://mail.python.org/mailman/listinfo/python-list