Python __hash__ Method
Last modified November 17, 2026 Python 3.15
The hash() built-in calls __hash__ to produce an
integer used by dictionaries and sets. Objects that compare equal must have
equal hashes, and the fields that feed the hash must not change while the
object is in a collection. This article shows the contract, immutable keys,
custom rules, hashable containers, and when a class should be unhashable.
The hash and equality contract
hash(obj) is evaluated as
type(obj).__hash__(obj). Python requires that a == b
implies hash(a) == hash(b), so a class that defines both methods
must use the same fields. A tuple of attributes is a convenient way to combine
them.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __repr__(self):
return f"Point({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(1, 2)
p3 = Point(3, 4)
print(p1 == p2)
print(hash(p1) == hash(p2))
print(len({p1, p2, p3}))
Two points with the same coordinates are equal and hash equally. The set
therefore keeps only one of them, leaving two members for three objects.
Returning NotImplemented from __eq__ for other types
avoids confusing comparisons.
$ python basic_hash.py True True 2
Hashable dictionary keys
A hashable object used as a key must keep its hash stable. Read-only
properties expose the fields, and __slots__ prevents adding new
attributes; the hash is computed from the same fields that equality compares.
class ImmutablePerson:
__slots__ = ("_name", "_age")
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@property
def age(self):
return self._age
def __hash__(self):
return hash((self._name, self._age))
def __eq__(self, other):
if not isinstance(other, ImmutablePerson):
return NotImplemented
return (self._name, self._age) == (other._name, other._age)
person = ImmutablePerson("Alice", 30)
d = {person: "value"}
print(d[person])
try:
person.name = "Bob"
except AttributeError as e:
print(type(e).__name__, e)
The person works as a dictionary key and is found on lookup. Assigning to
the read-only property raises AttributeError, so the public
interface cannot change the hash. The private fields are still reachable, so
the class relies on not mutating them; that is the real requirement for
hashability.
$ python immutable_hash.py value AttributeError property 'name' of 'ImmutablePerson' object has no setter
A custom hashing rule
The hash may use a normalised form of the data, provided equality uses the same form. Here text is casefolded once at construction, so different spellings produce the same key.
class Folded:
def __init__(self, text):
self.text = text.casefold()
def __hash__(self):
return hash(self.text)
def __eq__(self, other):
if not isinstance(other, Folded):
return NotImplemented
return self.text == other.text
a = Folded("Hello")
b = Folded("HELLO")
print(a == b)
print(hash(a) == hash(b))
d = {a: "value"}
print(d[b])
The two folded strings are equal, hash equally, and find the same
dictionary entry. Using casefold() rather than lower()
handles more Unicode cases. The __eq__ guard keeps comparisons
with unrelated objects from failing with an attribute error.
$ python custom_hash.py True True value
Hashable containers
A container can be hashable if it stores its contents in an immutable form. Converting the input to a tuple makes the hash stable while the class still offers indexing and length.
class FrozenList:
def __init__(self, items):
self._items = tuple(items)
def __hash__(self):
return hash(self._items)
def __eq__(self, other):
if not isinstance(other, FrozenList):
return NotImplemented
return self._items == other._items
def __getitem__(self, index):
return self._items[index]
def __len__(self):
return len(self._items)
def __repr__(self):
return f"FrozenList({list(self._items)})"
a = FrozenList([1, 2, 3])
b = FrozenList([1, 2, 3])
d = {a: "value"}
print(d[b])
print(len(d), list(a))
Two containers built from equal lists are equal and share a hash, so the second one finds the value stored under the first. The dictionary keeps a single entry. Exposing only reads protects the tuple from being changed through the public interface.
$ python hashable_container.py value 1 [1, 2, 3]
When to stay unhashable
Defining __eq__ without __hash__ makes a class
unhashable: Python sets __hash__ to None. That is the
correct choice when the fields used for equality can change, because a moved
object would no longer sit in the right bucket.
class MutablePoint:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
self.x += dx
self.y += dy
def __eq__(self, other):
if not isinstance(other, MutablePoint):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
p = MutablePoint(1, 2)
print(MutablePoint.__hash__)
try:
hash(p)
except TypeError as e:
print(type(e).__name__, e)
The printed None confirms the automatic assignment, and
hash(p) raises TypeError. If the point moved after
being inserted into a set, a hand-written hash based on its coordinates would
break lookup; leaving the class unhashable prevents that mistake.
$ python mutable_unhashable.py None TypeError unhashable type: 'MutablePoint'
Best practices
Hashability is a contract with the collections that store your objects:
- Equal objects must have equal hashes, and the reverse is not required.
- Hash only state that cannot change while the object is in a collection.
- Combine several fields with a tuple rather than arithmetic if readability matters.
- Implement
__eq__with the same fields as__hash__. - Leave mutable classes unhashable instead of writing a fragile hash.
Source
object.__hash__ - Python documentation
Hashable - Python documentation
object.__eq__ - Python documentation
In this article we have implemented the __hash__ method. We
have covered the equality contract, immutable keys, custom rules, containers,
and unhashable classes. For related topics, see
Python __eq__ method,
Python hash() function, and
Python dictionaries.
Author
List all Python tutorials.