Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I call hash() on an apparently hashable method of an unhashable instance?

Tags:

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?

like image 492
Zero Piraeus Avatar asked Mar 24 '15 17:03

Zero Piraeus


People also ask

How do I fix Unhashable type error?

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.

What does Unhashable type mean Python?

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.

How do I fix Unhashable type Numpy Ndarray?

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.

What does Unhashable mean?

"unhashable" means it cannot be used to build hash. Dictionaries use hash-functions to speed up access to values through keys.


1 Answers

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.

like image 200
Martijn Pieters Avatar answered Sep 21 '22 22:09

Martijn Pieters