Md. Mahmud Hasan
Md. Mahmud Hasan

Reputation: 1063

How to generate same hash value for python 2.7 and 3.4

I have generated a hash for two different function in two different project. One project used python 2.7 environment, other used python 3.4. I need to match those two hash.

    x=("asd","def")
    hash(x)

It's not matching. Any idea? Thanks in advance.

Upvotes: 1

Views: 1052

Answers (3)

Well, tough luck. The internal details of __hash__ is considered an implementation detail. Additionally, in Pythons since 3.3, the hash function of strings is randomized by default. The calculation differs from 32-bit versions to 64-bit versions (the value is truncated to Py_ssize_t).

However, if for example your Python 3.5 is 64-bit and Python 2.7 is 32-bit; you could try anding the Python 3 value with 0xFFFFFFFF to get the 2.7 value, e.g., if

>>> hash((1, 2, 3)) & 0xFFFFFFFF

works.

Upvotes: 3

catwith
catwith

Reputation: 1295

You can deterministally generate hash values using a hash function in hashlib:

import hashlib

hash_obj = hashlib.sha256(b"hello")
hex_hash = hash_obj.hexdigest()
print(hex_hash)
# Always prints: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

There are various kinds of hash functions available in the module, so see more on the hashlib documention.

Upvotes: 0

neu242
neu242

Reputation: 16620

Use py27hash for the same hash results in Python 3 & 2:

$ python2.7
>>> print(hash("test1234"))
1724133767363937712

$ python3
>>> print(hash("test1234"))
-2119032519227362575
>>> from py27hash.hash import hash27
>>> print(hash27("test1234"))
1724133767363937712

Upvotes: 1

Related Questions