I use this code to judge object can be hashed or not in python:
#hashable
number1 = 1.2 #float
number2 = 5 #int
str1 = '123' #str
tuple1 = (1,2,3) #tuple
# unhashable
list1 = [1,2,3] #list
print(hash(list1)) #TypeError: unhashable type: 'list'
set1 = {1,2,3} #set
print(hash(set1)) #TypeError: unhashable type: 'set'
dict1 = {'a':1,'b':2,'c':3} #dict
print(hash(dict1)) #TypeError: unhashable type: 'dict'
def HashableOrUnhashable(obj):
'''
This function will return True or False, the object can be hashed or not be hashed.
'''
try:
hash(obj)
return True
except Exception as ex:
return False
result = HashableOrUnhashable(someObj) #Can be str,int,float,list,tuple,set,dict or others.
if result:
print('This object can be hashed.')
else:
print('This object can not be hashed.')
I think my writing in the function HashableOrUnhashable
is not good.
So how should I judge whether an object can be hashed or not?