dictionary keys, __hash__, __cmp__
Michael Hudson
mwh at python.net
Wed Nov 5 08:16:58 EST 2003
Jan-Erik Meyer-Lütgens <python at meyer-luetgens.de> writes:
> In the Python Language Reference, I found the following
> statements about using objects as dictionary keys:
>
> 1. "__hash__() should return a 32-bit integer."
>
> 2. "The only required property is that objects which
> compare equal have the same hash value."
>
> 3. "If a class does not define a __cmp__() method it
> should not define a __hash__() operation either."
>
>
> Can I asume that:
>
> -- it is guaranteed that id(obj) returns a unique 32-bit integer
No. For instance it doesn't on a 64-bit platform (and on a ridiculous
64 bit platform *cough*Win64*cough* it might even return a long).
> -- keys are interchangeable (equivalent),
> if the following is valid:
>
> hash(key1) == hash(key2) and key1 == key2
Not quite sure what you mean by equivalent, but if that is true
a key inserted under key1 can be retrieved with key2.
> -- I can ignore the 2nd statement, if I am aware of
> the fact that: if objects are equal it dosn't mean that
> they are the same key.
Um, I don't understand you, but I think the answer is "no".
If you ever have a situation where hash(a) != hash(b) but a == b then
you are very much breaking the rules.
> -- I can savely ignore the 3rd statement, because python
> falls back to cmp(id(obj1), id(obj2)), if __cmp__()
> is not defined.
Don't understand.
Cheers,
mwh
--
I wouldn't trust the Anglo-Saxons for much anything else. Given
they way English is spelled, who could trust them on _anything_ that
had to do with writing things down, anyway?
-- Erik Naggum, comp.lang.lisp
More information about the Python-list
mailing list