Search code examples
pythonpython-3.xhashlib

How to create separate instances of a hash algorithm in Python?


hashlib contains implementations for hash algorithms. Unfortunately two consecuting calls to hashlib.sha256() do not produce two different instances of SHA256 but the same one: If called twice hashlib.sha256() will return the same object each time. So apparently we have a singleton here

This is bad in a all situations where any kind of concurrency is required. Additionally this is very bad in situations where you want to provide a hashing object to some algorithm. In my case: Tests fail as the same object is reused instead of creating a new one.

My question: How an I create two instances of SHA256 (or any other hash algorithm)?

Example:

import hashlib

print(hashlib.sha256())
print(hashlib.sha256())

This will output something like:

<sha256 HASH object @ 0x7fb3611b4710>
<sha256 HASH object @ 0x7fb3611b4710>

Solution

  • In your first example, the second hash-object is created after your first hash-object was garbage-collected. Therefore they can have the same memory address. In hashlib.sha256() is hashlib.sha256() the first one can't be garbage-collected since it has to be compared first. You can save the hash-objects in varibles to keep them alive:

    h1 = hashlib.sha256()
    h2 = hashlib.sha256()
    print(h1 is h2)
    
    [Output]
    False