Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Why Python functions are hashable?
An object in Python is hashable if it has a hash value that remains the same during its lifetime. It must have a __hash__() method and be comparable to other objects via __eq__(). If two hashable objects are equal when compared, they have the same hash value.
Being hashable makes an object usable as a dictionary key and a set member, since these data structures use hash values internally. All immutable built-in objects in Python are hashable. Mutable containers like lists and dictionaries are not hashable, while immutable containers like tuples are.
Objects that are instances of user-defined classes are hashable by default − they all compare unequal (except with themselves), and their hash value is derived from their id().
Why Are Python Functions Hashable?
Python functions are hashable because they are objects with a fixed identity throughout their lifetime. Each function object has a unique memory address (returned by id()), a __hash__() method, and can be compared using __eq__(). This means functions can be used as keys in dictionaries and as members of sets.
Example: Hash and ID of a Function
In this example, we compare the hash value and id of a function to see how they relate ?
def f():
pass
print("type:", type(f))
print("hash:", hash(f))
print("id: ", id(f))
print("__hash__:", f.__hash__())
The output of the above code is ?
type: <class 'function'> hash: 8772367116842 id: 140357873869472 __hash__: 8772367116842
Note that the hash value is derived from but not necessarily equal to the id(). The same applies to lambda functions ?
Example: Hash of a Lambda Function
m = lambda x: 1
print("hash:", hash(m))
print("id: ", id(m))
The output of the above code is ?
hash: 8772367116842 id: 140357873869472
Using Functions as Dictionary Keys
Since functions are hashable, they can be used directly as dictionary keys. This can be useful for dispatch tables or mapping operations to their implementations ?
Example
def cat_info():
return "Cats are small mammals with fur."
def dog_info():
return "Dogs are four-legged mammals."
# Use functions as dictionary keys
animals = {
cat_info: cat_info(),
dog_info: dog_info()
}
for func, info in animals.items():
print(f"{func.__name__}: {info}")
The output of the above code is ?
cat_info: Cats are small mammals with fur. dog_info: Dogs are four-legged mammals.
Using Functions in Sets
Functions can also be added to sets since sets require their elements to be hashable ?
Example
def add(x, y):
return x + y
def subtract(x, y):
return x - y
operations = {add, subtract}
print("Number of operations:", len(operations))
for op in operations:
print(f"{op.__name__}(10, 3) = {op(10, 3)}")
The output of the above code is ?
Number of operations: 2 subtract(10, 3) = 7 add(10, 3) = 13
Conclusion
Python functions are hashable because they are objects with a stable identity, a __hash__() method, and support for equality comparison. This allows them to be used as dictionary keys and set members, enabling patterns like dispatch tables and function registries.
