So start with the question i.e. Why and how are Python functions hashable? First, one should know what actually hashable means in Python. So, hashable is a feature of Python objects that tells if the object has a hash value or not. If the object has a hash value then it can be used as a key for a dictionary or as an element in a set.
An object is hashable if it has a hash value that does not change during its entire lifetime. Python has a built-in hash method ( __hash__() ) that can be compared to other objects. For comparing it needs __eq__() or __cmp__() method and if the hashable objects are equal then they have the same hash value. All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable.Â
Objects which are instances of the user-defined class are hashable by default, they all compare unequal, and their hash value is their id().
Example: Consider two tuples t1, t2 with the same values, and see the differences:
Python3
t1 = ( 1 , 5 , 6 ) Â
t2 = ( 1 , 5 , 6 ) Â
# show the id of object print ( id (t1)) Â
print ( id (t2)) |
Â
Â
Output:
Â
140040984150664 140040984150880
Â
In the above example, two objects are different as for immutable types the hash value depends on the data stored not on their id.
Â
Example: Let’s see lambda functions are hashable or not.
Â
Python3
# create a one-line function l = lambda x : 1 Â
# show the hash value print ( hash (l)) Â
# show the id value print ( id (l)) Â
# show the hash value print (l.__hash__()) |
Â
Â
Output:
Â
-9223363246992694337 140637793303544 -9223363246992694337
Â
Hence, lambda functions are hashable.
Â
Example: Let’s see user defined def based function are hashable or not.
Â
Python3
# create an empty function def fun(): Â Â pass Â
# print types of function print ( type (fun)) Â
# print hash value print (fun.__hash__()) Â
# print hash value print ( hash (fun)) |
Â
Â
Output:
Â
<class 'function'> -9223363242199589441 -9223363242199589441
Â
Therefore, any user defined function is hashable as its hash value remains same during its lifetime.
Â