Repaso
Español
PythonAdvancedPY-11

A class defines __eq__ but not __hash__. What happens when you add an instance to a set?

Options

  1. It uses the default identity hash
  2. TypeError: unhashable type (Correct option)
  3. It works but duplicates are allowed
  4. It uses __eq__ to compute a hash

Answer

TypeError: unhashable type

Why

Sets and dictionary keys find objects by their hash (a number calculated from the object).

The rule is: equal objects must have the same hash. When you write your own __eq__, Python cannot be sure the old hash still follows that rule, so it sets __hash__ = None.

The object becomes unhashable and adding it to a set raises TypeError. Define __hash__ using the same fields you compare in __eq__.

Remember

Override __eq__ → also define __hash__ if you need sets or dict keys.

Key terms

Practice this question in Repaso