hashkey/digest for a complex object

Duncan Booth duncan.booth at invalid.invalid
Wed Oct 6 15:13:50 EDT 2010


kj <no.email at please.post> wrote:

> The short version of this question is: where can I find the algorithm
> used by the tuple class's __hash__ method?
> 

http://svn.python.org/view/python/trunk/Objects/tupleobject.c?revision=81029&view=markup

static long
tuplehash(PyTupleObject *v)
{
    register long x, y;
    register Py_ssize_t len = Py_SIZE(v);
    register PyObject **p;
    long mult = 1000003L;
    x = 0x345678L;
    p = v->ob_item;
    while (--len >= 0) {
        y = PyObject_Hash(*p++);
        if (y == -1)
            return -1;
        x = (x ^ y) * mult;
        /* the cast might truncate len; that doesn't change hash stability */
        mult += (long)(82520L + len + len);
    }
    x += 97531L;
    if (x == -1)
        x = -2;
    return x;
}



> I'm looking for a good algorithm for computing a hash key for
> something like this?  (Basically I'm looking for a good way to
> combine hashkeys.)

If you want to combine the hashes from several objects then the 
easiest way is just to create a tuple of the objects and hash it.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list