Hash values are just integers that are used to compare dictionary keys during a dictionary lookup quickly.
Internally, hash()
method calls __hash__()
method of an object which is set by default for any object. We'll look at this later.
The syntax of hash()
method is:
hash(object)
hash() Parameters
hash()
method takes a single parameter:
- object - the object whose hash value is to be returned (integer, string, float)
Return value from hash()
hash()
method returns the hash value of an object if it has one.
If an object has custom __hash__()
method, it truncates the return value to the size of Py_ssize_t
.
Example 1: How hash() works in Python?
# hash for integer unchanged
print('Hash for 181 is:', hash(181))
# hash for decimal
print('Hash for 181.23 is:',hash(181.23))
# hash for string
print('Hash for Python is:', hash('Python'))
Output
Hash for 181 is: 181 Hash for 181.23 is: 530343892119126197 Hash for Python is: 2230730083538390373
Example 2: hash() for immutable tuple object?
hash()
method only works for immutable objects as tuple.
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
print('The hash is:', hash(vowels))
Output
The hash is: -695778075465126279
How hash() works for custom objects?
As stated above, hash()
method internally calls __hash__()
method. So, any objects can override __hash__()
for custom hash values.
But for correct hash implementation, __hash__()
should always return an integer. And, both __eq__()
and __hash__()
methods have to be implemented.
Below are the cases for correct __hash__()
override.
__eq__() | __hash__() | Description |
---|---|---|
Defined (by default) | Defined (by default) | If left as is, all objects compare unequal (except themselves) |
(If mutable) Defined | Should not be defined | Implementation of hashable collection requires key's hash value be immutable |
Not defined | Should not be defined | If __eq__() isn't defined, __hash__() should not be defined. |
Defined | Not defined | Class instances will not be usable as hashable collection. __hash__() implicity set to None . Raises TypeError exception if tried to retrieve the hash. |
Defined | Retain from Parent | __hash__ = <ParentClass>.__hash__ |
Defined | Doesn't want to hash | __hash__ = None . Raises TypeError exception if tried to retrieve the hash. |
Example 3: hash() for Custom Objects by overriding __hash__()
class Person:
def __init__(self, age, name):
self.age = age
self.name = name
def __eq__(self, other):
return self.age == other.age and self.name == other.name
def __hash__(self):
print('The hash is:')
return hash((self.age, self.name))
person = Person(23, 'Adam')
print(hash(person))
Output
The hash is: 3785419240612877014
Note: You don't have to implement __eq__()
method for the hash as it is created by default for all objects.