[Python-Dev] 'unhashable type' and new style classes

Guido van Rossum guido@python.org
Mon, 30 Dec 2002 11:30:10 -0500


> > > This code
> > > 
> > >   class X:
> > >       def __cmp__(self, other):
> > >           return 1
> > > 
> > >   c1 = X()
> > > 
> > >   d = {}
> > >   d[c1] = None
> > > 
> > > raises a TypeError, unhashable type, since the class does
> > > not define a __hash__ method.
> > > 
> > > This error is no longer raised when X derives from object.
> > > Bug (or feature)?
> > 
> > It's something in between. :-(
> > 
> > I've been struggling with this since 2.2 and not found a good
> > solution.  Built-in mutable types like list and dict deal with this by
> > having an explicit tp_hash slot that raises an exception.
> 
> Why doesn't the default implementation raise a TypeError (or be NULL),
> and the immutable types override this?

The default implementation of __hash__ must match the default
implementation of __cmp__ (and rich comparisons, __eq__ etc.).  So the
default implementation cannot raise an exception, because objects are
defined to be immutable by default.  (Maybe this was a mistake, but
it's not so easy to change without causing backwards
incompatibilities.)

> > Can you add a SF entry and assign it to me?  Any insight you might
> > have in the matter would be appreciated.
> 
> Sure.

Thanks.

--Guido van Rossum (home page: http://www.python.org/~guido/)