1

I'm trying to build a function that calculates hashed for a file. The function takes to arguments, the file name and the algorithm to generate:

def getHashValue(fName, Hash):
   f = open(fName, 'rb')
   hashvalue = hashlib.Hash(f.read()).hexdigest
   f.close()
   print(fName + str(Hash) + hashvalue)

My problem is that I'm unable to get the Hash argument to work. The idea was if I ad md5 I will get this:

hashvalue = hashlib.md5(f.read()).hexdigest

Andy.l

1
  • So you want to choose the hash algorithm dynamically from the argument?
    – user395760
    Mar 3, 2011 at 17:31

4 Answers 4

10

Don't use hashlib inside the function. Just take the function as a parameter and use it.

def getHashValue(fName,Hash):
   f = open(fName,'rb')
   hashvalue = Hash(f.read()).hexdigest
   f.close()
   print(fName + str(Hash) + hashvalue)

Then when you call this function, use:

getHashValue(filename, hashlib.md5)

If you want to get the hash function from a string, use getattr.

hashvalue = getattr(hashlib, Hash)(f.read()).hexdigest

And call this one with:

getHashValue(filename, 'md5')
1
  • 1
    +1 For recommending the (more robust) solution of passing a function first, and not reaching straight for runtime lookup with getattr.
    – phooji
    Mar 3, 2011 at 17:37
0

You're looking for getattr:

hashvalue = getattr(hashlib, Hash)(f.read()).hexdigest
0

You must pass the hash argument as a string and use getattr.

Like this:

def getHashValue(fName, hash):
    f = open(fName, 'rb')
    hashfun = getattr(hashlib, hash) # Here you assign the function to a variable just to simplify
    hashvalue = hashfun(f.read()).hexdigest
    f.close()

Then you can call: getHashValue("foo.txt", "md5")

And you should get the result you want. Be careful, though, you should handle the cases where the hash algorithm does not exist (for instance you used "xyz" instead of "md5" or something).

3
  • Neves, I've implemented your sugestion and added a return hasvalue, and doesn't get any result. If I add print(hashvalue)I get an python message saying: built-in method hexdigest of _hashlib.HASH object at 0x025C55C0
    – de-diac
    Mar 3, 2011 at 18:34
  • added () at the end of hashvalue = hashfun(f.read()).hexdigest and it worked.
    – de-diac
    Mar 3, 2011 at 18:40
  • Whoops, sorry about that. :) Lack of sleep does not help me coding. Mar 4, 2011 at 10:10
0

Assuming Hash is a str, you will need to use "getattr" to get the function you want:

def getHashValue(fName,Hash):
   f = open(fName,'rb')
   hashvalue = getattr(hashlib,Hash)(f.read()).hexdigest
   f.close()
   print(fName + str(Hash) + hashvalue)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.