Hash functions

Michael Hudson mwh at python.net
Thu Jul 21 12:42:22 EDT 2005


Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:

> Do people often use hash() on built-in types? 

Only implicitly.

> What do you find it useful for?

Dictionaries :)

> How about on custom classes?

Same here.

> Can anyone give me some good tips or hints for writing and using
> hash functions in Python?

Well, the usual tip for writing them is, don't, unless you need to.

If implement __eq__, then you need to, so it's fairly common to just
hash a tuple containing the things that are considered by the __eq__
method.  Something like:

class C(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    def __eq__(self, other):
        return self.a == other.a and self.b == other.b
    def __hash__(self):
        return hash((self.a, self.b))

Cheers,
mwh

-- 
  I'm a keen cyclist and I stop at red lights.  Those who don't need
  hitting with a great big slapping machine.
                                           -- Colin Davidson, cam.misc



More information about the Python-list mailing list