objects as mutable dictionary keys

Nick Coghlan ncoghlan at iinet.net.au
Wed Dec 29 14:04:19 CET 2004


> Yeah, that looks like a pretty decent summary to me.  I wonder if this 
> would be worth posting on the Wiki somewhere?  Maybe:
> 
> http://www.python.org/moin/DictionaryKeys
> 
> That makes it easy to point to when this issue comes up again.

The page may also want to mention an extant bug with new-style classes.

The behaviour is *meant* to be:

1. Class defines none of __cmp__, __eq__ or __hash__:
   Default behaviour allows the class to be used as an identity-based dictionary 
key.

2. Class defines __hash__ and __cmp__ (or __eq__):
   Class is usable as a dictionary key, with semantics governed by developer 
supplied methods.

3. Class defines __cmp__ or __eq__, but NOT __hash__:
   Class cannot be used as a dictionary key, as the default hash may not be 
valid for the developer supplied comparison operation.

For classic classes, this works as expected. For new-style classes, case 3 
doesn't work properly - the default hash is inherited from object anyway.

This *is* a bug (since Guido called it such), but one not yet fixed as the 
obvious solution (removing object.__hash__) causes problems for Jython, and a 
non-obvious solution has not been identified.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list