How to instatiate a class of which the name is only known at runtime?

Peter Otten __peter__ at
Tue Sep 16 01:56:33 CEST 2003

Tomasz Lisowski wrote:

>> import sys
>> def getClass(classname, modulename):
>>     try:
>>         module = sys.modules[modulename]
>>     except KeyError:
>>         module = __import__(modulename)
>>     return getattr(module, classname)
> Hmm...
> Why not write it directly:
> def getClass(classname, modulename):
>     try:
>         module = __import__(modulename)
>     except ImportError:
>         return None
>     else:
>         return getattr(module, classname)
> I have heard, that the __import__ function is smart enough to check the
> sys.modules dictionary without actually re-importing the once imported
> module. Is it true?

I think you are right with respect to __import__(). However, it's a bad idea
to catch the import error. Your client code should have determined the
module name beforehand, so that something has gone seriously wrong when you
get an ImportError. Returning None instead of a class only confuses the
issue (nobody wants to go back to the C habit of checking every function's
return value for an errorr code). So:

def getClass(classname, modulename):
    return getattr(__import__(modulename), classname)

would be a shorter equivalent to my getClass(). It seems that a lookup in
sys.modules is done implicitely by __import__(), as I tested it
successfully with "__main__" as the module name.

Note that all three versions will not work with submodules, e. g. "os.path",
so let's change it one more (last?) time:

def getClass(classname, modulename):
    return getattr(__import__(modulename, globals(), locals(), [classname]),


More information about the Python-list mailing list