Making unhashable object

O

Olive

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:
Traceback (most recent call last):
File said:
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
 
C

Chris Angelico

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:
def __init__(self,a):
self.value=a
__hash__=None

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
 
P

Peter Otten

Olive said:
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:
Traceback (most recent call last):
File said:
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:
.... __hash__ = None
....Traceback (most recent call last):
.... __hash__ = None
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'B'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top