Python hash()

The hash() method returns the hash value of an object if it has one. Hash values are just integers that are used to compare dictionary keys during a dictionary look quickly.

Example


hash() Syntax

The syntax of hash() method is:

hash(object)

hash() Parameters

The hash() method takes a single parameter:

  • object - the object whose hash value is to be returned (integer, string, float)

hash() Return Value

The hash() method returns the hash value of an object.


Example 1: How hash() works in 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.

Output

The hash is: -695778075465126279

How does hash() work 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__()

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.