PYTHONHASHSEED在Python 2和3之间统一

时间:2017-11-10 11:51:47

标签: python python-2.7 hash python-3.5

我想为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下的相同调用会导致测试通过。

0 个答案:

没有答案