In programming, a hashable object is one that can be used as a key in a dictionary or as an element in a set. This requires the object to have certain properties to ensure its hash value is consistent and reliable throughout its lifetime. Here are the key properties and concepts related to hashable objects:
__hash__()
method that returns an integer[2][3].__eq__()
method. Objects that compare as equal must have the same hash value[1][3].A hash function is a function that takes input data of arbitrary size and converts it into a fixed-size value, called a hash value or hash. A good hash function has several key properties:
Custom classes in Python are hashable by default if they do not override the __hash__
method. By default, their hash value is derived from their identity (memory address), which ensures that each instance has a unique hash value[1][4]. However, best practice is to explicitly define the __hash__
method if custom equality behavior is implemented with __eq__
[2].
class ImmutablePoint:
def __init__(self, x, y):
self._x = x
self._y = y
def __eq__(self, other):
if not isinstance(other, ImmutablePoint):
return False
return self._x == other._x and self._y == other._y
def __hash__(self):
return hash((self._x, self._y))
@property
def x(self):
return self._x
@property
def y(self):
return self._y
In this example, ImmutablePoint
is hashable because it has a consistent hash value derived from its immutable attributes _x
and _y
, and it can be compared to other ImmutablePoint
objects[3].
Hashable objects play a crucial role in data structures like dictionaries and sets, enabling efficient data storage and retrieval. The key properties of hashable objects—consistent hash value, equality comparison, and immutability—ensure that these data structures function correctly and efficiently.