python的散列函数在不同版本中保持相同吗? [英] Does python's hash function remain identical across different versions?

查看:144
本文介绍了python的散列函数在不同版本中保持相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在整数和字符串的元组(以及整数和字符串的嵌套元组等)上使用 hash 来计算某些对象的唯一性。除了可能存在散列冲突,我想知道 - 对于那些保证为不同版本的Python返回相同结果的数据类型, hash 函数

解决方案

没有。除了32位和64位版本的Python之间的长期差异之外,哈希算法已更改在Python 3.3中来解决安全问题:
$ b


默认情况下,哈希的str,字节和日期时间对象被盐与一个不可预知的随机值。尽管它们在单独的Python过程中保持不变,但在重复调用Python之间它们是不可预测的。



这是为了防止拒绝服务仔细选择输入,利用最差情况下的字典插入,O(n ^ 2)复杂性。请参阅 http://www.ocert.org/advisories/ocert-2011-003.html 以获取详细信息。

更改散列值会影响字典,集合和其他映射的迭代顺序。 Python从来没有对这个顺序做过保证(它通常在32位和64位版本之间有所不同)。

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


I'm currently using hash on tuples of integers and strings (and nested tuples of integers and strings etc.) in order to compute the uniqueness of some objects. Barring that there might be a hash collisions, I wonder - is the hash function on those data types guaranteed to return the same result for different versions of Python?

解决方案

No. Apart from long-standing differences between 32- and 64-bit versions of Python, the hashing algorithm was changed in Python 3.3 to resolve a security issue:

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).

As a result, from 3.3 onwards hash() is not even guaranteed to return the same result across different invocations of the same Python version.

这篇关于python的散列函数在不同版本中保持相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆