Hashable
and Unhashable
objects?An object is hashable
if its hash value never changes during its lifetime. All of Python’s immutable built-in objects(such as strings
and tuples
) are hashable, while mutable containers (such as lists
or dictionaries
) are unhashable
.
Objects which are instances of user-defined classes are hashable by default. The immutability of an object enables Python to derive its hash value.
Hashability makes an object usable as a dictionary key and a set member because these data structures use the hash value internally.
Python built-in data-structure set
to the rescue.
If you try to add an unhashable object into a set, it will throw a TypeError exception
def check_hashable(an_object):
try:
set().add(an_object)
print("The object is hashable")
except TypeError:
print("The object is unhashable")
>>> check_hashable(100)
The object is hashable
>>> check_hashable("mystring")
The object is hashable
>>> check_hashable([1, 2, 3, 4])
The object is unhashable
>>> check_hashable((1, 2, 3, 4))
The object is hashable
>>> check_hashable({"blog-name": "realnitinworks", "author": "Nitin"})
The object is unhashable
We try to add the object to a set inside the try...except
block. If it throws a TypeError
exception, the object is not hashable, otherwise, it is hashable.
Hashable
classThe Hashable
class is available in collections.abc
- An abstract base class for containers
from collections.abc import Hashable
def check_hashable(an_object):
if isinstance(an_object, Hashable):
print("The object is hashable")
else:
print("The object is unhashable")
>>> check_hashable(100)
The object is hashable
>>> check_hashable("mystring")
The object is hashable
>>> check_hashable([1, 2, 3, 4])
The object is unhashable
In the above code, we use the built-in isinstance
function to check if the passed-in object is an instance of Hashable or not.
We have seen what does it means to be hashable or unhashable with respect to an object. I also introduced two methods to check if an object is hashable or not.
Leave a comment