Use Hash value in python code #memo

Recently when I reading a code and test it, the code didn’t work. ;( The code used python hash function for generating some values. This is the reason why the code didn’t work in python3. Python3 hash function returns same value in only same session.

So it should not use as permanent value. For example…

$ python -c "print(hash('a'));"
-6739920846501962706

$ python -c "print(hash('a'));"
2223204068672557918

Now I god different value from same string object ‘a’. Next, I used hashlib.

$ python -c "import hashlib;m=hashlib.md5(b'a').digest();print(m)"
b'\x0c\xc1u\xb9\xc0\xf1\xb6\xa81\xc3\x99\xe2iw&a

$ python -c "import hashlib;m=hashlib.md5(b'a').digest();print(m)"
b'\x0c\xc1u\xb9\xc0\xf1\xb6\xa81\xc3\x99\xe2iw&a

Next I could got same hashed value from binary object.

To get same value with hash() function for testing, set PYTHONHASHSEED value in environment value is required. https://docs.python.org/3.7/using/cmdline.html?highlight=hashseed#envvar-PYTHONHASHSEED

$ export PYTHONHASHSEED=0
$ python -c "print(hash('a'));"
-7583489610679606711
$ python -c "print(hash('a'));"
-7583489610679606711

It just memorandum for me….

Advertisement

Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: