Equal objects must have equal hashes.
Objects that compare equal must have hashes that compare equal.
OK got it.
However, not all objects with the equal hashes compare equal themselves.
That's the one I find confusing -- why is it not "bad" for two objects with the same has (the 42 example above) to not be equal? That seems like it would be very dangerous. Is this because it's possible, if very unlikely, for ANY hash algorithm to create the same hash for two different inputs? So equality always has to be checked anyway?
From a practical standpoint, think of dictionaries:
(that's the trick here -- you can't "get" this without knowing something about the implementation details of dicts.)
- objects are sorted into buckets based on their hash
- any one bucket can have several items with equal hashes
is this mostly because there are many more possible hashes than buckets?
- those several items (obviously) will not compare equal
So the hash is a fast way to put stuff in buckets, so you only need to compare with the others that end up in the same bucket?
- 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 here's my question: if there is only one object in that bucket, is __eq__ checked anyway?
If so, then yes, can see why it's not dangerous (if potentially slow) to have a bunch of unequal objects with the same hash.
So, if an object's hash changes, then it will no longer be findable in
any hash table (dict, set, etc.).
That part, I think I got.
So what happens when there is no __eq__?The object can still be hashable -- I guess that's because there IS an __eq__ -- it defaults to an id check, yes?