In Python, the hash() function is used to obtain the hash value of a given object.
A hash value is an integer with the following characteristics:
- For the same object, the hash value remains constant across different executions of the program.
- Different objects may have the same hash value, but this probability is very small.
The hash() function takes one parameter, the object to calculate the hash value for, and returns that object's hash value (if it has one).
Note: Not all objects can be hashed. Only immutable objects can be hashed, such as numbers, strings, tuples, etc. Mutable objects (like lists, dictionaries, sets) cannot be hashed. Attempting to hash a mutable object will raise a TypeError exception.
hash() Function Examples
a = "hello world"
print(hash(a)) # Random each run
print(hash(a)) # But same within the same run
b = (1, 2, 3)
print(hash(b))
c = [1, 2, 3]
d = {}
# print(hash(c)) # TypeError
# print(hash(d)) # TypeError
__hash__() Method
Objects can implement their own __hash__() method. The hash() function performs a bitwise AND operation between the return value of __hash__() and 0xffffffffffffffff, truncating the return value according to the machine's word size (e.g., keeping only the lower 64 bits on a 64-bit machine).
class myClass:
def __init__(self, value):
self.value = value
def __hash__(self):
return self.value
a = myClass(1234567890)
print(hash(a)) # 1234567890
a.value = 12345678901234567890
print(hash(a)) # 816463855166098135
b = 12345678901234567890 & 0xffffffffffffffff # Keep only lower 64 bits
print(hash(b)) # 816463855166098135