Let's say I have a dictionary:
>>> d = {}
It has a method clear()
:
>>> d.clear <built-in method clear of dict object at 0x7f209051c988>
... which has a __hash__
attribute:
>>> d.clear.__hash__ <method-wrapper '__hash__' of builtin_function_or_method object at 0x7f2090456288>
... which is callable:
>>> callable(d.clear.__hash__) True
So why can't I hash it?
>>> hash(d.clear) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict'
Note: I know that dict
objects are unhashable – I'm curious as to why this restriction extends to their methods, even though, as noted above, they appear to claim otherwise?
This error occurs when trying to hash a list, which is an unhashable object. For example, using a list as a key in a Python dictionary will cause this error since dictionaries only accept hashable data types as a key. The standard way to solve this issue is to cast a list to a tuple, which is a hashable data type.
TypeError: unhashable type: 'list' usually means that you are trying to use a list as an hash argument. This means that when you try to hash an unhashable object it will result an error. For ex. when you use a list as a key in the dictionary , this cannot be done because lists can't be hashed.
We can solve this by adding each array element instead of the array object into the set. This should add all the elements of the array to the set.
"unhashable" means it cannot be used to build hash. Dictionaries use hash-functions to speed up access to values through keys.
It is a bound method, and bound methods have a reference to self
, e.g. the dictionary. This makes the method un-hashable.
You can hash the unbound dict.clear
method:
>>> d = {} >>> d.clear.__self__ {} >>> d.clear.__self__ is d True >>> hash(d.clear) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> hash(dict.clear) -9223372036586189204
Methods on instances that are hashable will themselves be hashable, so the object type for built-in bound methods implements a __hash__
method but raises TypeError
when the __self__
attribute is not hashable. This is consistent with the object.__hash__
method documentation; if you can set it to None
or not implement it at all then that is preferable but for these cases where the hashability is only known at runtime raising a TypeError
is the only option available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With