Are user-defined objects good keys?

Greg Weeks weeks at vitus.scs.agilent.com
Sat Sep 29 16:12:48 EDT 2001


The issue of identity, equality, and hashing strikes me as unsettled in
general.  And, in my opinion, Python "got it wrong".  But I don't want to
thrash out this issue.  I'd just like to know how to program.  So:

Suppose I define a class.  I don't define __cmp__; so two instances are
"==" iff they have the same id.  I also don't define __hash__.  Also, the
instances are mutable.

Let inst be an instance, and let n be an integer.  In my python
installation, the following are true:

A.    hash(n) == n
B.    hash(inst) == hash(id(inst))

Regarding A: Is hash() used to create hash indices for dictionaries?  If
so, is the identity function a good hash function for integer keys?

Regarding B: Is B true for all python implementations?  If not, then is it
true that

C.    hash(inst) == fn(id(inst))

for *some* function fn()?  If either B or C is true, then most user-defined
mutable instances can be used as dictionary keys.  (I say "most" because
most user-defined mutable instances will not redefine __cmp__.)

My central question is: Can I use user-defined mutable instances (that are
"==" iff their ids are equal) as dictionary keys?  On my system I can.
What about others?

Regards,
Greg



More information about the Python-list mailing list