[Python-Dev] Documentation Error for __hash__

M.-A. Lemburg mal at egenix.com
Fri Aug 29 11:53:28 CEST 2008


On 2008-08-28 21:31, Michael Foord wrote:
> Hello all,
> 
> The documentation for __hash__ seems to be outdated. I'm happy to submit
> a patch, so long as I am not misunderstanding something.
> 
> http://docs.python.org/dev/reference/datamodel.html#object.__hash__
> 
> The documentation states:
> 
> If a class does not define a __cmp__() or __eq__() method it should not
> define a __hash__() operation either; if it defines __cmp__() or
> __eq__() but not __hash__(), its instances will not be usable as
> dictionary keys. If a class defines mutable objects and implements a
> __cmp__() or __eq__() method, it should not implement __hash__(), since
> the dictionary implementation requires that a key's hash value is
> immutable (if the object's hash value changes, it will be in the wrong
> hash bucket).
> 
> 
> This may have been true for old style classes, but as new style classes
> inherit a default __hash__ from object - mutable objects *will* be
> usable as dictionary keys (hashed on identity) *unless* they implement a
> __hash__ method that raises a type error.

Being hashable is a different from being usable as dictionary key.

Dictionaries perform the lookup based on the hash value, but will
then have to check for hash collisions based on an equal comparison.

If an object does not define an equal comparison, then it is not
usable as dictionary key.

> Shouldn't the advice be that classes that implement comparison methods
> should always implement __hash__ (wasn't this nearly enforced?),

It's probably a good idea to implement __hash__ for objects that
implement comparisons, but it won't always work and it is certainly
not needed, unless you intend to use them as dictionary keys.

> and that mutable objects should raise a TypeError in __hash__.

That's a good idea, even though it's not needed either ;-)

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Aug 29 2008)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611


More information about the Python-Dev mailing list