de-diac
de-diac

Reputation: 439

Unable to pass a variable to function

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

Upvotes: 1

Views: 782

Answers (4)

Jonathan Sternberg
Jonathan Sternberg

Reputation: 6647

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')

Upvotes: 10

goertzenator
goertzenator

Reputation: 2039

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)

Upvotes: 0

João Neves
João Neves

Reputation: 957

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).

Upvotes: 0

phihag
phihag

Reputation: 287855

You're looking for getattr:

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

Upvotes: 0

Related Questions