On 7/27/20 11:15 AM, Christopher Barker wrote:
On Sun, Jul 26, 2020 at 8:25 PM Guido van Rossum wrote:
In fact, defining `__hash__` as returning the constant `42` is better, because it is fine if two objects that *don't* compare equal still have the same hash value (but not the other way around).
Really? can anyone recommend something to read so I can "get" this -- it's counter intuitive to me. Is __eq__ always checked?!? I recently was faced with dealing with this issue in updating some old code, and I'm still a bit confused about the relationship between __hash__ and __eq__, and main Python docs did not clarify it for me.
Equal objects must have equal hashes. Objects that compare equal must have hashes that compare equal.
However, not all objects with the equal hashes compare equal themselves.
From a practical standpoint, think of dictionaries:
adding ------ - objects are sorted into buckets based on their hash - any one bucket can have several items with equal hashes - those several items (obviously) will not compare equal
retrieving ---------- - get the hash of the object - find the bucket that would hold that hash - find the already stored objects with the same hash - use __eq__ on each one to find the match
So, if an object's hash changes, then it will no longer be findable in any hash table (dict, set, etc.).