Hashability?

James Henderson james at logicalprogression.net
Mon Jul 19 15:30:21 CEST 2004


On Monday 19 July 2004 3:50 am, Chris S. wrote:
> Perhaps this is obvious to some, but why are dictionary keys constrained
> to hashable objects?

I'm not sure exactly what you mean here.  My definition of a "hashable object" 
would be one that can serve as a dictionary key.  This is basically all 
classes whose instances, when they compare equal, have the same hash value.  

> why not use the object's id for the hash value.
> Wouldn't this allow typically non-hashable objects to be used as keys?
> I've done this in several instances and I've never encountered a problem.

By default user-defined class do use their ID as their hash value and this is 
fine because by default instances of user-defined classes do not compare 
equal.  If you go and define a __cmp__() method for your class and there is a 
danger of instances comparing equal then you need to define the __hash__() 
method too.  See the sections on __cmp__() and __hash__() in:

http://www.python.org/doc/current/ref/customization.html

Note that Python doesn't even stop you using an immutable type (say a subclass 
of the built-in list type) as a dictionary key if you give it a __hash__() 
method.  See the following very bad code. :)

>>> class MyList(list):
...     def __hash__(self): return 1
...
>>> l1 = MyList(range(10))
>>> l1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l2 = MyList(range(10, 20))
>>> d = {l1: 1, l2: 2}
>>> d
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: 1, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: 
2}

James
-- 
James Henderson, Logical Progression Ltd
http://www.logicalprogression.net
http://mailmanager.sourceforge.net




More information about the Python-list mailing list