Javier Novoa C. Javier Novoa C. - 1 year ago 172
Python Question

Python dynamic instantiation from string name of a class in dynamically imported module

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:

loader-class script:

import sys
class loader:
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!
except ImportError:
# manage import error

some-dynamically-loaded-module script:

class myName:
# etc...

I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...

Any ideas are appreciated.

Answer Source

You can use getattr

getattr(module, class_name)

to access the class. More complete code:

module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download