Sobes.tech
Junior — Middle

How is data hashing implemented in the Python interpreter?

sobes.tech AI

Answer from AI

In the Python interpreter (CPython), hashing is implemented through the built-in function __hash__, which is defined for many built-in data types such as strings, numbers, tuples, etc. For immutable objects, the hash is computed based on their content, allowing them to be used as keys in dictionaries and sets.

For example, for strings, the hash is calculated using an algorithm based on polynomial rolling with a specific constant. For numbers, the hash is usually the number itself (with some nuances for float and other types).

In CPython, hashes are cached for immutable objects to speed up repeated access. For user-defined classes, you can define the __hash__ method to specify your own hashing method.

Example of a user-defined class with hashing:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return isinstance(other, Point) and self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash((self.x, self.y))

p1 = Point(1, 2)
p2 = Point(1, 2)
print(hash(p1) == hash(p2))  # True

Thus, hashing in Python is based on computing an integer value that uniquely (as much as possible) reflects the object's content and is used for fast lookup and comparison.