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

Peter Otten __peter__ at web.de
Wed Sep 10 09:49:00 CEST 2003


Marco Herrn wrote:

> 1. How to do the import? I didn't find a way to give a string to the
>    import statement.
> 
> 2. How to write such code to instantiate?

Off topic: This thread like some others is spread over a few toplevel
entries in my newsreader (KNode 0.7.2). Is this a bug?

Anyway, putting it all together:

import sys

def getClass(classname, modulename):
    try:
        module = sys.modules[modulename]
    except KeyError:
        module = __import__(modulename)
    return getattr(module, classname)

print getClass("WichmannHill", "random")
print getClass("WichmannHill", "random")()


Peter




More information about the Python-list mailing list