1

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.

Deneb
  • 119
  • 1
  • 2
  • 10

2 Answers2

6

You can use getattr:

import hashlib
if self.hash_type in ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']:
     func = getattr(hashlib, self.hash_type)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

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)
Rob Watts
  • 6,866
  • 3
  • 39
  • 58
  • This also seems like a very good example. I was thinking of using a dictionary, but then I though it would make my code a little too messy. – Deneb Mar 03 '14 at 20:04
  • 1
    I prefer this way if you are just trying to get data, but when you are actually accessing function, I feel like Ashwini's answer is more pythonic. – Rob Watts Mar 03 '14 at 20:06