I am generating class names dynamically and then want to import that class by its name to access a static method.
This is the class to import in "the_module.py":
class ToImport(object):
@classmethod
def initialize(cls, parameter):
print parameter
According to a Blog post this is as far as I came:
theModule = __import__("the_module")
toImport = getattr(theModule, "ToImport")
toImport.initialize("parameter")
But the blog example seems to be incomplete as it gives me a module object without my desired class ToImport
. Looking at the __import__()
documentation shows me that there are more optional attributes to the function. I succeeded with
theModule = __import__("the_module", globals(), locals(), ["ToImport"])
Why do I have to give the fromlist
attribute? Can't I import all the modules attributes?