문제

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