Making unhashable object

Chris Angelico rosuav at gmail.com
Tue Feb 19 14:46:21 CET 2013


On Wed, Feb 20, 2013 at 12:38 AM, Olive
<diolu.remove_this_part at bigfoot.com> 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

This is an old-style class. If you subclass object, it works as you expect:

>>> class A(object):
    def __init__(self,a):
        self.value=a
    __hash__=None

>>> a=A(3)
>>> hash(a)

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    hash(a)
TypeError: unhashable type: 'A'

This is with Python 2.6. With Python 3 and later, that distinction no
longer exists.

ChrisA



More information about the Python-list mailing list