In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:
def __init__(self, module_name, class_name): # both args are strings
modul = sys.modules[module_name]
instance = modul.class_name() # obviously this doesn't works, here is my main problem!
# manage import error
You can use getattr
to access the class. More complete code:
module = __import__(module_name) class_ = getattr(module, class_name) instance = class_()