Sobes.tech
Junior — Middle

Can you explain how data hashing function is implemented in Python?

sobes.tech AI

Answer from AI

In Python, the hash function is implemented through the built-in hash() method, which returns an integer value — the hash of the object. For built-in immutable types (such as strings, numbers, tuples), specialized hashing algorithms are implemented, optimized for fast computation and uniform distribution.

For example, the algorithm used for strings processes characters sequentially and combines their codes using arithmetic operations (addition, multiplication) to produce the final hash.

Custom objects can implement the __hash__() method to define their own hashing method.

Example usage:

print(hash("example"))  # Outputs the integer hash value of the string

class MyClass:
    def __init__(self, value):
        self.value = value
    def __hash__(self):
        return hash(self.value)

obj = MyClass(10)
print(hash(obj))

Important: starting from Python 3.3, a random seed is used for string hashing to protect against DoS attack types.