Use a variable to fetch an object attribute (Python)

Sometimes you want to use a variable to contain the name of an attribute that you might later want to fetch from an object. For example, if you're doing hashing operations you might want to have the algorithm name in a variable, and use that in order to trigger behaviour (rather than having a massive if block, duplicating calls).

Details

  • Language: Python

Snippet

getattr(object,attributename)

Usage Example

# Example to grab an instance of the relevant hashlib object                   
# Using the first command line argument
import hashlib    
import sys

algo=sys.argv[1]

hashing=getattr(hashlib,algo)