Skip to main content

Python hash() Function

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.

danger

hash() method only works for immutable objects!

If you try to use the hash() method on a mutable object such as a list or a dictionary, you will get an error.

Syntax

hash(object)

hash() Parameters

Python hash() function parameters:

ParameterConditionDescription
objectRequiredobject whose hash value is to be returned

hash() Return Value

Python hash() function returns the hash value of an object.

Examples

Example 1: hash() function with Integer, Float and String

# hash for integer unchanged
print('Hash for 123 is:', hash(123))

# hash for decimal
print('Hash for 123.45 is:',hash(123.45))

# hash for string
print('Hash for Python is:', hash('Python'))

output

Hash for 123 is: 123
Hash for 123.45 is: 1037629354146168955
Hash for Python is: 1892538395206928408

Example 2: hash() on immutable object

Notice that hash() method only works for immutable objects, like Tuple.

For example, let's compute the hash of this tuple:

vowels = ('a', 'e', 'i', 'o', 'u')
print('The hash is:', hash(vowels))

output

The hash is: 5517348902720630840

hash() function for custom objects

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.

These are the cases for correct override of __hash__() function:

__eq__()__hash__()Description
Defined (by default)Defined (by default)If left as is, all objects compare unequal (except themselves)
(If mutable) DefinedShould not be definedImplementation of hashable collection requires key's hash value be immutable
Not definedShould not be definedIf __eq__() isn't defined, __hash__() should not be defined.
DefinedNot definedClass instances will not be usable as hashable collection. __hash__() implicits set to None. Raises TypeError exception if tried to retrieve the hash.
DefinedRetain from Parent__hash__ = <ParentClass>.__hash__
DefinedDoesn't want to hash__hash__ = None. Raises TypeError exception if tried to retrieve the hash.

Example: 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(25, 'Tom')
print(hash(person))

output

The hash is:
5027081020790499504
note

You do not have to implement __eq__() method for the hash as it is created by default for all objects.