Skip to the solution
MediumDSA13 min read

What is the __hash__ and __eq__ contract?

456 views

The problem

Question presented to candidate: "If I write a class and want to use its instances as dictionary keys or put them in a set, what do __eq__ and __hash__ have to do, and what goes wrong if they disagree?"

What a strong answer should cover:

  • The contract: if a == b then hash(a) == hash(b); the reverse is not required (collisions are allowed). A hash must also stay the same for the object's whole life while it is in a set or dict.
  • Defaults: plain objects compare and hash by identity. Defining __eq__ without __hash__ makes Python 3 set __hash__ = None, so instances become unhashable (TypeError: unhashable type).
  • How dicts and sets use it: hash picks the slot, then identity is checked, then __eq__; breaking the contract gives silent duplicates or lookups that miss.
  • Implement both from the same immutable fields: __eq__ compares a tuple of fields (returning NotImplemented for other types), __hash__ returns hash() of the same tuple; mutable objects should not be hashable.
  • Tools and details: @dataclass(frozen=True) generates both, eq=True alone removes the hash, unsafe_hash=True is risky; 1 == 1.0 == True share a hash; string hashes are randomised per process (default since 3.3).

Clarifying questions expected:

  • Will the objects be mutated after they are added to a set or used as keys?

Code / implementation expected: Yes β€” a value class with consistent __eq__/__hash__, and a demonstration of what breaks when the contract is violated or a key is mutated.

  • hashing
  • eq

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThe contract, the __eq__-only trap, broken hashes and mutated keys
PythonHow dicts call __eq__, NaN, dataclasses and subclasses

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 91 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What does the functools module offer?

Continue