I know very well that it is not good practice using eval in Python. Here is my code:

from hashlib import * # added for clarification
def get_hash(self):
        if self.hash_type in ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']:
            data = eval(self.hash_type) # <--- how can I replace this?

I've heard of the setattr function, but I honestly don't know how to implement it.

Is it also possible to do this by using the map function?

Note that 'md5', 'sha1', 'sha224' etc are local variables. When I'm using the eval function on one of them, they become functions.

有帮助吗?

解决方案

You can use getattr:

import hashlib
if self.hash_type in ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']:
     func = getattr(hashlib, self.hash_type)

其他提示

Why not store all the information in a dictionary? For example:

self.hash_types = {
    'md5': md5,
    'sha1': sha1,
    ...
}

Then in get_hash:

def get_hash(self):
    if self.hash_type in self.hash_types:
        data = self.hash_types[self.hash_type]

Alternatively,

def get_hash(self):
    data = self.hash_types.get(self.hash_type, self.DEFAULT)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top