dictionary keys, __hash__, __cmp__

Michael Hudson mwh at python.net
Wed Nov 5 12:46:42 EST 2003


Jan-Erik Meyer-Lütgens  <python at meyer-luetgens.de> writes:

> Michael Hudson wrote:
> > Jan-Erik Meyer-Lütgens  <python at meyer-luetgens.de> writes:
> >>Michael Hudson wrote:
> >>>Jan-Erik Meyer-Lütgens  <python at meyer-luetgens.de> writes:
> >>>
> >>>>   3. "If a class does not define a __cmp__() method it
> >>>>       should not define a __hash__() operation either."
> >>>>
> >>
> >>Ok, let me ask the following question: What is the reason
> >>for that rule?
> > Well, the idea is that dictionary lookup is done by equality.  If you
> > don't define __cmp__ then equality is in fact identity (well, that's
> > very nearly true...) so the default implementation of __hash__ (based
> 
> ...and the full truth is? :-)

Oh, something to do with __coerce__ and instances of old-style classes
(well, I didn't mention __eq__ either, but I assume you know about
that).

> > on the pointer address) is as good as it can get (you have hash
> > equality iff you have object equality).
> > I think.
> > 
> 
> So, this rule is a hint, only. It could break performance,
> not functionality, if I define my own hash function, right?
> 
> 
> To make things totally clear, I repeat my question:
> 
> The only thing to be aware of when working with keys (besides
> of object immutability) seems the following:
> 
> Keys are equivalent (in the sense of: a key inserted under
> key1 can be retrieved with key2), if this is valid:
> 
>     hash(key1) == hash(key2) and key1 == key2
> 
> Is this guaranteed? 

Yes.

> In future implementations?

One can't predict the entire future of course -- hey, maybe dicts will
be splay trees or something one day -- but *I* would be happy
depending on it.

Cheers,
mwh

-- 
42. You can measure a programmer's perspective by noting his
    attitude on the continuing vitality of FORTRAN.
  -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html




More information about the Python-list mailing list