gpt4 book ai didi

python - python的哈希函数在不同版本之间是否保持相同?

转载 作者:行者123 更新时间:2023-12-04 13:14:00 29 4
gpt4 key购买 nike

我目前在整数和字符串的元组(以及整数和字符串的嵌套元组等)上使用hash,以计算某些对象的唯一性。除非存在哈希冲突,否则我想知道-这些数据类型上的hash函数是否保证对于不同版本的Python返回相同的结果?

最佳答案

否。除了32位和64位版本的Python之间的长期差异之外,哈希算法was changed in Python 3.3可以解决安全问题:

By default, the hash() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).


结果,从3.3版本开始, hash()甚至不能保证在相同Python版本的不同调用之间返回相同结果。

关于python - python的哈希函数在不同版本之间是否保持相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16452252/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com