Python Reference ยท Classes and Special Methods
__eq__() and __hash__()
Reference for Python __eq__() and __hash__(): defining equality, why overriding __eq__ makes a class unhashable, the hash contract and dict/set behavior.
__eq__() defines what == means for your objects, and __hash__() returns the integer used to place them in sets and as dictionary keys. The two must agree: objects that compare equal must have the same hash.
By default objects are equal only to themselves, and their hash comes from their identity. As soon as you define __eq__() in a class, Python sets __hash__ to None, making instances unhashable until you define __hash__() too.
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y) def __hash__(self): return hash((self.x, self.y))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class C: def __eq__(self, other) -> bool: ... def __ne__(self, other) -> bool: ... def __hash__(self) -> int: ...
| Method | Description |
|---|---|
__eq__(self, other) |
Implements self == other. Return NotImplemented for types you do not know. |
__ne__(self, other) |
Implements !=. By default it inverts __eq__() (unless that returns NotImplemented), so you rarely write it. |
__hash__(self) |
Returns an int. Python reduces it to its own size if needed. |
Return value: __eq__() normally returns a bool (any object is allowed). __hash__() returns an int.
Raises: TypeError: unhashable type when you hash an object whose __hash__ is None.
Usage notes
- Return
NotImplemented, notFalse, for foreign types. Python then tries the reflected operation on the other object and finally falls back to identity. - The contract: if
a == bthenhash(a) == hash(b). Break it and dictionaries and sets behave unpredictably. - Hash only immutable data. If the fields used in the hash change after the object is in a set or dict, lookups fail. Hash a tuple of exactly the fields that
__eq__()compares. - Defining
__eq__clears__hash__. To keep identity hashing you must say so explicitly:__hash__ = object.__hash__(rarely wise). - Intentionally unhashable. For mutable value objects, leaving
__hash__asNoneis correct. @dataclassgenerates__eq__()and, withfrozen=Trueoreq=True, unsafe_hash=True, a matching__hash__(). Plain@dataclassmakes instances unhashable.- Numbers.
1 == 1.0 == Trueand they hash alike, so they share one dictionary key. - Containers use
==after identity.x in listchecksx is item or x == item. - Hash randomization. String hashes differ between runs, so never rely on exact values or set ordering.