我想为Python 2.7和Python 3.5版本获取相同的字典字符串。我硬编码PYTHONHASHSEED
如下:
$ source ~/virtualenv/bin/activate
$ python --version
Python 2.7.12
$ PYTHONHASHSEED=0 python -c "print({'one':2,'two':3,'three':4})"
{'three': 4, 'two': 3, 'one': 2}
$ source ~/virtualenv-python3/bin/activate
$ python --version
Python 3.5.2
$ PYTHONHASHSEED=0 python -c "print({'one':2,'two':3,'three':4})"
{'two': 3, 'three': 4, 'one': 2}
为什么这两次调用会产生不同的输出?有没有办法找到PYTHONHASHSEED
的值,为Python 2.7和Python 3.5提供相同的结果?
更新
我的真实案例:
encoding_case.py
import base64
import json
def sth_to_call(b64_of_dict):
raise NotImplementedError(
'This is simulation of independent resources '
'and this should be mocked. That is why I am raising otherwise.'
)
def f(**kwargs):
sth_to_call(base64.b64encode(json.dumps(kwargs).encode()))
test_encoding_case.py
import mock
import unittest
import encoding_case
class EncodingCaseTest(unittest.TestCase):
@mock.patch('encoding_case.sth_to_call')
def test_f(self, sth_to_call_mock):
encoding_case.f(**{'one': 2, 'two': 3, 'three': 4})
sth_to_call_mock\
.assert_called_with(b'eyJ0d28iOiAzLCAidGhyZWUiOiA0LCAib25lIjogMn0=')
在Python 2.7下调用PYTHONHASHSEED=0 nosetests test_encoding_case
时出现错误:
AssertionError: Expected call: sth_to_call('eyJ0d28iOiAzLCAidGhyZWUiOiA0LCAib25lIjogMn0=')
Actual call: sth_to_call('eyJvbmUiOiAyLCAidGhyZWUiOiA0LCAidHdvIjogM30=')
Python 3.5下的相同调用会导致测试通过。