A class defines __eq__ but not __hash__. What happens when you add an instance to a set?
Options
- It uses the default identity hash
- TypeError: unhashable type (Correct option)
- It works but duplicates are allowed
- 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.