lost Hashability with __cmp__

Alex Martelli aleax at aleax.it
Wed Jan 29 17:12:51 CET 2003


Martin Schmettow wrote:

> I declared a __cmp__ for a class. Now I get an TypeError: unhashable
> instance if  I use objects of this class as keys in a dictionary.
> Can someone explain why and how I can gain back hashability?

When your class X defines none of __cmp__, __eq__, and __hash__,
then for any instance x of X, hash(x) returns id(x) -- no problem.

If you have __cmp__ or __eq__ but no __hash__, this means your
class is not hashable -- the case you're in now.

To make it hashable again, define __hash__: remember it MUST
return the same value for any two objects that compare equal,
AND it must always return the SAME value for any single given
object (the two constraints taken together practically mean
such objects must be immutable in all that concern their
comparison for equality).


Alex





More information about the Python-list mailing list