Sobes.tech
Junior — Middle

Explain how object comparison is implemented via __eq__ when these objects are used as keys in a dictionary.

sobes.tech AI

Answer from AI

In Python, objects used as dictionary keys must be hashable. When a key is added to a dictionary, the object's __hash__ method is called to determine the bucket in the hash table. If a collision occurs during key lookup (different objects with the same hash), the __eq__ method is called to compare objects for equality.

Therefore, for the dictionary to work correctly, it is important that:

  • If two objects are equal according to __eq__, their hashes (__hash__) should also match.
  • The __eq__ method should correctly define object equality.

Example:

class MyKey:
    def __init__(self, val):
        self.val = val

    def __eq__(self, other):
        if isinstance(other, MyKey):
            return self.val == other.val
        return False

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

key1 = MyKey(10)
key2 = MyKey(10)

my_dict = {key1: 'value'}
print(my_dict[key2])  # Will output 'value' because key1 == key2 and hashes match

If __eq__ is implemented but __hash__ is missing or implemented incorrectly, the dictionary may not work properly.