When is hash(n) == n in Python?

前端 未结 4 466
广开言路
广开言路 2021-01-30 05:08

I\'ve been playing with Python\'s hash function. For small integers, it appears hash(n) == n always. However this does not extend to large numbers:

         


        
4条回答
  •  心在旅途
    2021-01-30 05:40

    The implementation for the int type in cpython can be found here.

    It just returns the value, except for -1, than it returns -2:

    static long
    int_hash(PyIntObject *v)
    {
        /* XXX If this is changed, you also need to change the way
           Python's long, float and complex types are hashed. */
        long x = v -> ob_ival;
        if (x == -1)
            x = -2;
        return x;
    }
    

提交回复
热议问题