在 Python 中,字符串(str
类型)、字面值(bytes
类型)和日期类型(datetime.datetime
类型)的哈希值,只保证了在同一个解释器里相同(同一个解释器的不同进程之间也相同)。
这是因为 Python 中 hash()
函数在计算以上类型的哈希值时,需要用到环境参数 PYTHONHASHSEED
。PYTHONHASHSEED
参数可以在启动 Python 脚本时设置,如果不设置的话则将在 [0,4294967295]
范围内随机生成。只有需要求哈希值的对象相同,且 PYTHONHASHSEED
也相同,计算得出的哈希值才会相同。
环境参数 PYTHONHASHSEED
只能在启动 Python 脚本时设置,Python 脚本启动后无法修改,只能通过 os.environ["PYTHONHASHSEED"]
查看。
在各个环境中的设置方法如下:
- 在 Windows 环境中,可以将其添加到环境变量中。
- 在 Linux 环境中,可以在启动脚本时添加环境变量,类似:
PYTHONHASHSEED=0 python test.py
- PyCharm 设置
PYTHONHASHSEED
环境变量的方法如下:Run(菜单栏) - Edit Configurations(下拉菜单) - Run/Debug Configurations(子窗口) - Configuration(子窗口内的选项卡) - Environment(选项卡中的标题) - Environment variables(选项卡中的一项) 中添加 PYTHONHASHSEED=0
参数(注意和其他参数用 ;
间隔)
参考文档
Python 3.10 的文档中对 PYTHONHASHSEED 的文档如下(文档地址):
If this variable is not set or set to random, a random value is used to seed the hashes of str, bytes and datetime objects.
If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.
Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.
The integer must be a decimal number in the range [0,4294967295]. Specifying the value 0 will disable hash randomization.
New in version 3.2.3.
CPython 中对 PYTHONHASHSEED 的注释如下(文档地址):
"PYTHONHASHSEED: if this variable is set to 'random', a random value is used\n"
" to seed the hashes of str and bytes objects. It can also be set to an\n"
" integer in the range [0,4294967295] to get hash values with a\n"
" predictable seed.\n"