The hash()
function returns the hash value for the given object. With that function, there are two ways to test if an object is hashable:
- Using a
try/except
block; - Using the
isinstance()
function withtyping.Hashable
.
try/except
Block
try:
hash(my_object) # Attempt to hash the object
print("My object is hashable.")
except TypeError:
print("My object is not hashable.")
You could also try to add the object to a set
instead of using the hash()
function.