How to create an object by getting the name of a class from a string (the class is in another module)?

    2 answers 2

    To load a module dynamically and create an object from a string:

    import importlib modulename, dot, classname = "pkg.your_module.ClassName".rpartition('.') module = importlib.import_module(modulename) klass = getattr(module, classname) instance = klass() 

      If in the forehead, I would do this:

      testClass.py

       class TestClass(object): def __init__(self): self.name = "Hello, TestClass!" 

      testImport.py

       moduleName = "testClass" className = "TestClass" exec("from " + moduleName + " import " + className) exec("fileObject =" + className + "()") print fileObject.name 

      Test

       >>> python testImport.py >>> Hello, TestClass! 

      But this trash code, IMHO. In general, I would look at other implementations, I thought many times to write a system of plug-ins for my program.