Possible Duplicate:
Dynamic module import in Python
Probably a simple question! I need to iterate through a list of classes (as strings) passed from a settings file. The classes are listed like below:
TWO_FACTOR_BACKENDS = (
'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication
'id.backends.TOTPBackend',
'id.backends.HOTPBackend',
#'id.backends.YubikeyBackend',
#'id.backends.OneTimePadBackend',
#'id.backends.EmailBackend',
)
I now need to call the authenticate() function on each of these classes (unless commented out, of course). I’m happily iterating through the list, I just need to know how to convert the strings to a Class object in my foreach loop so that I can call the authenticate method on it. Is there an easy way to do this?
You want to use the
importlibmodule to handle loading of modules like this, then simply usegetattr()to get the classes.For example, say I have a module,
somemodule.pywhich contains the classTest:Gives me:
It’s trivial to add in things like packages:
And it will not import a module/package if it’s already been imported, so you can happily do this without keeping track of loading modules: