String Hashes Change Between Python Runs

hash() of a str or bytes gives the same result within one process, but a different one in the next run, because Python salts it with a random value chosen at startup. Never store or share hash() results; use hashlib when you need a stable digest.

$ python3 -c 'print(hash("abc"))'
-8748397559819712012
$ python3 -c 'print(hash("abc"))'
-7961601321481834535
  • The randomness is deliberate. Since Python 3.3, salted hashing stops attackers from crafting keys that all collide in one dict bucket and slow a server to a crawl.

  • Only str, bytes, and datetime are salted. Numbers hash the same everywhere: hash(42) == 42.

  • For a value that is the same in every run, use hashlib:

    import hashlib
    
    hashlib.sha256(b"abc").hexdigest()  # identical in every run
  • To reproduce a run exactly, for example in a test, fix the salt with the PYTHONHASHSEED environment variable (PYTHONHASHSEED=0).