Sobes.tech
Middle

What needs to be implemented in a class to make it hashable?

sobes.tech AI

Answer from AI

To make a class in Python hashable, you need to implement two methods: __eq__ and __hash__.

  1. __eq__(self, other): This method defines the equality comparison operation (==). It should accept another object other and return True if the objects are equal, and False otherwise.
  2. __hash__(self): This method should return an integer hash value of the object. If a == b is always true, then hash(a) should also be equal to hash(b). The hash should remain constant during the lifetime of the object.

If you implement only __eq__ but not __hash__, Python will automatically assign __hash__ the value None, making the object unhashable. If you implement only __hash__ but not __eq__, Python will use the default comparison implementation (by identifier), which can lead to incorrect behavior when using objects in hashable collections.

Classes containing mutable attributes generally should not be hashable, as changing an attribute after computing the hash violates the invariant that the hash of an object remains constant during its lifetime.

Example:

class MyImmutableClass:
    def __init__(self, value):
        self.value = value  # Attribute that does not change after initialization

    def __eq__(self, other):
        if not isinstance(other, MyImmutableClass):
            return NotImplemented
        return self.value == other.value

    def __hash__(self):
        return hash(self.value)