QA
Intermediate LevelPython

Why must you implement __hash__() whenever you implement custom __eq__() for objects stored in Sets or Dict keys?

❓ Interview Prompt: Explain hashability, `__hash__()`, `__eq__()`, hash collisions, stored keys in Dicts/Sets, and preserving object immutability.

For an object to be stored as a Dictionary key or Set element, it MUST be hashable:

The Golden Rule of Hashing:

If two objects evaluate as equal ('a == b'), they MUST have identical hash values ('hash(a) == hash(b)')!

•
Overriding '__eq__' zeroes out '__hash__': If you implement custom '__eq__', Python sets '__hash__ = None' to prevent bugs. You must implement custom '__hash__()' based on immutable attributes!

Code Implementation Example

python
class Person:
    def __init__(self, ssn, name):
        self.ssn = ssn
        self.name = name
        
    def __eq__(self, other):
        return isinstance(other, Person) and self.ssn == other.ssn
        
    def __hash__(self):
        return hash(self.ssn) # Hash based on unique immutable attribute!

p1 = Person('123-45', 'Alice')
p2 = Person('123-45', 'Alice')
people_set = {p1, p2}
print(len(people_set)) # 1 (Duplicate correctly identified!)
💡Implementing __hash__ alongside __eq__ for Set element storage.
🎯 Interview Key Takeaway

Always implement __hash__ based on immutable fields whenever you implement custom __eq__.

#__hash__#__eq__#Hashable#Sets#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?