Why doesn't Python hash function give the same values when run on Android implementation?

前端 未结 5 724
-上瘾入骨i
-上瘾入骨i 2020-12-09 15:44

I believed that hash() function works the same in all python interpreters. But it differs when I run it on my mobile using python for android. I get same hash v

5条回答
  •  臣服心动
    2020-12-09 16:20

    for old python (at least, my Python 2.7), it seems that

    hash() = id() / 16
    

    and for CPython id() is the address in memory - http://docs.python.org/2/library/functions.html#id

    >>> id(int) / hash(int)                                                     
    16                                                                              
    >>> id(int) % hash(int)                                                 
    0                                                                               
    

    so my guess is that the Android port has some strange convention for memory addresses?

    anyway, given the above, hashes for types (and other built-ins i guess) will differ across installs because functions are at different addresses.

    in contrast, hashes for values (what i think you mean by "non-internal objects") (before the random stuff was added) are calculated from their values and so likely repeatable.

    PS but there's at least one more CPython wrinkle:

    >>> for i in range(-1000,1000):
    ...     if hash(i) != i: print(i)
    ...
    -1
    

    there's an answer here somewhere explaining that one...

提交回复
热议问题