__hash__ not in genindex.html

Steven Taschuk staschuk at telusplanet.net
Wed May 28 12:01:26 EDT 2003


Quoth Thomas Güttler:
> class Doc(dict):
>     pass
>     def __str__(self):
>         return "<Doc: %s>" % dict.__str__(self)
>     def __hash__(self):
>         return id(self)
> 
> Since dicts are normaly unhashable, I did the __hash__ method
> like above. Are there any problems with this method? Why don't
> all dictionaries have __hash__ like this?

It's not obvious that hashing dicts by identity is the Right
Thing; perhaps it would be better to hash by value, say by
    def __hash__(self):
        items = self.items()
        items.sort()
        return hash(tuple(items))
This way the code
    metadict = {}
    metadict[{'k': 3}] = 'foo'
    print metadict[{'k': 3}]
would print 'foo', as one might naively expect.

Neither hashing by identity nor hashing by value is obviously
right here, so...  refuse the temptation to guess.  Make the
programmer state explicitly the behaviour they want.

> It would be nice if __hash__ would be in:
>  http://www.python.org/doc/lib/genindex.html

Hm... but __hash__ is not documented in the Library Reference, so
it's not obvious what such an index entry would refer to.

The other __foo__ in the Library Reference index are actually from
the operator module, which does not include hash(), since that's a
built-in function anyway.  (Note that hash() *is* documented in
the Library Reference
    <http://www.python.org/doc/lib/built-in-funcs.html#l2h-26>
and does appear in the index.)

__hash__ is documented among the other special methods in the
Language Reference
    <http://www.python.org/doc/ref/customization.html#l2h-97>
and appears in the corresponding index.

(An amalgamated index for all the documentation might be useful.)

-- 
Steven Taschuk                            staschuk at telusplanet.net
Every public frenzy produces legislation purporting to address it.
                                                  (Kinsley's Law)





More information about the Python-list mailing list