简体   繁体   中英

How to reuse an instance of hashlib.md5

How do you flush (or reset) and reuse an instance of hashlib.md5 in python? If I am performing multiple hashing operations in a script, it seems inefficient to use a new instance of hashlib.md5 each time, but from the python documentation I don't see any way to flush or reset the instance.

Why do you think it's inefficient to make a new one? It's a small object, and objects are created and destroyed all the time. Use a new one, and don't worry about it.

Here's what I did, just write a little wrapper that reinitializes the hash object. Handles the clunkiness of the code writing, but maybe not the efficiency at runtime.

def Hasher(object):
    def __init__(self):
        self.md5 = hashlib.md5()

    def get_hash(self, o):
        self.md5.update(o)
        my_hash = self.md5.digest()
        self.md5 = hashlib.md5()
        return my_hash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM