I want to use all available hashlib algorithms to hash the same file

I’m asking about the first line of the hash_function function.
Can I use the value of a variable as the attribute of hashlib, instead of the name of the variable, as happens here:

import hashlib

def hash_function(style):
    hasher = hashlib.style()  # <
    with open('1.webp', 'rb') as afile:
        buf = afile.read()
        hasher.update(buf)
        print(hasher.hexdigest())

for item in hashlib.algorithms_available:
    print(item)
    hash_function(item)

OUTPUT:
shake_128
Traceback (most recent call last):
  File "whathash.py", line 13, in <module>
    hash_function(item)
  File "whathash.py", line 4, in hash_function
    hasher = hashlib.style()
AttributeError: module 'hashlib' has no attribute 'style'

In this case, it uses ‘style’ as the attribute, but I want it to use ‘shake_128’.

You want hashlib.new(style) instead of hashlib.style().

Also keep in mind that for the SHAKE digests, a length parameter is required for the hexdigest() call.

Thank you.

In the specific case of hashlib, @dtrodrigues has given the best possible answer; but in general, there’s also another thing you can do. Every time you do thing.attribute, you can rewrite that as getattr(thing, "attribute") - and since the attribute name is just a string now, that can come from a variable. VERY useful when iterating over the dir() of a module or object!

Thanks.
Can you recommend a good python reference book? At the moment I’m using Python Crash Course by Eric Matthes, which is very up to date, but doesn’t cover very much. It doesn’t mention getattr, for example.

Dead-tree book? No, sorry; haven’t delved into them so I can’t make any recommendations (I know there are some good ones out there, but I’m not going to recommend something I don’t personally know).

What I tend to point people to is the main Python tutorial, and for web programming, the Django Girls tutorial. Both are excellent. (Coding is definitely for girls, and also for people who don’t consider themselves girls, and I recommend that tutorial regardless of someone’s gender.)

Thanks for the advice.