2

hash() method in python can match all immutable objects to unique hash value. However, I cannot understand the behavior of hash() method for objects of user-defined classes. Some of the resources say that if user-defined class do not contain __hash__() and __eq__() methods, that object cannot be hashed. On the other hand, the others claim the opposite one.

In other words, what is the role of __eq__() and __hash__() methods in order to hash custom objects ?

Goktug
  • 855
  • 1
  • 8
  • 21
  • Custom methods => custom implementation. No custom methods => default implementation. –  Mar 29 '18 at 10:25
  • 1
    Possible duplicate of [What do you mean by hashable in Python?](https://stackoverflow.com/questions/14535730/what-do-you-mean-by-hashable-in-python) – Aran-Fey Mar 29 '18 at 10:28

2 Answers2

0

If you don't implement __hash__, hash() will use the default implementation. If you don't implement __eq__, the default implementation will be used when you compare two instances.

class C:
    pass

class D:
    def __hash__(self):
        return 1

    def __eq__(self, other):
        return True

print(hash(C()))  # changing for every C instance
print(C() == C()) # False since objects are different

print(hash(D()))  # always 1
print(D() == D()) # always True
0

Basically, 'hash' should be quick, and act as a "triage" calculation to know if two objects are equal or not.

The 'eq' should precisely be the function that tells if the objects are definitely equal or not. Maybe this funciton has to perform a lot of checks ( for instance if you want to define the equality of your objects by the equality of all the member fields, and maybe there is are a lot of them)

The purpose of these two functions is to have a quick way of saying "no, they are not equal" (the hash function), since the comparisons are often used a lot, and most often two objects are not supposed to be "equals".

Instead of executing a lot of "eq" functions, you execute a lot of quick "hash" functions, and if both the hashes match, you execute "eq" to confirm the equality or not.

Pac0
  • 21,465
  • 8
  • 65
  • 74