In Python3 any class will have a default __hash__ which calculates a hash based on the member variables. I can set it (explicitly or implicitly) to None in order make the class non-hashable, which certainly has some usecases.
But are there reasons to override __hash__?
I couldn't find one.
Yes! Any time you override
__eq__, and also want to be able to use the object as the key in a set or dict. This is especially common in value types, or cases where your objects represent real world entities.__hash__does not hash member variables at all. For an object without__hash__or__eq__defined, it returns some value based on its internal pointer. If__eq__is defined, then invoking the method will cause a TypeError.workConsider this simple case where that default
__eq__and__hash__behavior isn't great:This has some weird behavior:
me == currentUser()is false, andpasswords[currentUser()]throws a KeyError. So to try to fix it, we define an__eq__:Now the
me == currentUser()is true, but trying to assign the password throws aTypeError: unhashable type: 'User'. Now we've gotten to the point where we want to override__hash__:And now it behaves like you'd expect any other such object to behave when you use it as a key.