views:

135

answers:

1

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?

+2  A: 

I have done exactly what you did and I retrieved the class.

In [1]: theModule = __import__("the_module")

In [2]: toImport = getattr(theModule, "ToImport")

In [3]: toImport.initialize("parameter")
parameter

I am using Python 2.6.4. Could you explain further, what exactly doesn't work for you?

gruszczy
Works for me as well, tested on Python 2.6.2 (Ubuntu) and Python 2.5.1 (Mac)
Daniel Hepper