Python Hashable
What Is Hashable?
A hashable object is one that has a hash value that never changes during its lifetime. Hashable objects can be used as keys in dictionaries and as elements in sets. In Python, an object is hashable if it implements the __hash__()
method and does not change its value after creation (is immutable).
The collections.abc.Hashable
abstract base class (ABC) is used to test whether an object is hashable.
The hash Method
To be hashable, a class must implement the __hash__(self)
method, which returns an integer hash value:
class MyHashable:
def __hash__(self):
return 42
obj = MyHashable()
print(hash(obj)) # 42
Using collections.abc.Hashable
You can check if a class or object is hashable using isinstance
or issubclass
:
from collections.abc import Hashable
print(isinstance(42, Hashable)) # True (int is hashable)
print(isinstance([1, 2, 3], Hashable)) # False (list is not hashable)
Most built-in immutable types (int, float, str, tuple) are hashable. Mutable types like list and dict are not hashable by default.
Why Use Hashable?
- To make your custom classes usable as dictionary keys or set elements.
- To use type checking and static analysis tools that recognize the Hashable ABC.
- To clarify intent in your code and documentation.
Concrete Example: Custom Hashable Class
Suppose you want to use a custom object as a key in a dictionary. You must make it hashable by implementing __hash__()
and __eq__()
:
from collections.abc import Hashable
class Point(Hashable):
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return isinstance(other, Point) and self.x == other.x and self.y == other.y
p1 = Point(1, 2)
p2 = Point(1, 2)
d = {p1: "A point!"}
print(d[p2]) # 'A point!' (p1 and p2 are considered equal and have the same hash)
- This allows you to use
Point
objects as dictionary keys or set elements.
Summary
collections.abc.Hashable
is the base class for objects that can be used as dict keys or set elements.- Requires the
__hash__()
method. - Used for type checking and to build custom hashable types.