Making unhashable object

Peter Otten __peter__ at web.de
Tue Feb 19 08:54:50 EST 2013


Olive wrote:

> I am trying to define a class whose instances should not be hashable,
> following:
> http://docs.python.org/2/reference/datamodel.html#object.__hash__
> 
> class A:
>     def __init__(self,a):
>         self.value=a
>     __hash__=None
>     
> 
> Then:
> 
>>>> a=A(3)
>>>> hash(a)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'NoneType' object is not callable
>>>> hash([2])
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unhashable type: 'list'
> 
> I would expect the same error in both case and the error is confusing in
> the first case. What's the proper way of making an object non hashable?
> 
> Olive

Deriving your classes from object has several advantages, among them:

>>> class A:
...     __hash__ = None
... 
>>> hash(A())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> class B(object):
...     __hash__ = None
... 
>>> hash(B())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'B'





More information about the Python-list mailing list