Loading a class the name of which is only known runtime

Bjarke Dahl Ebert bjarke-news2003 at trebe.dk
Tue Apr 8 15:01:56 EDT 2003


"Mads Orbesen Troest" <mads at troest.NEVERMORE.dk> wrote in message

> Actually, what I am looking for is more alone the lines of:
>
> moduleToImport = "SomeModule" # <- Retrieved as CGI argument
> classToInstantiate = "SomeClass" # <- Retrieved as CGI argument
>
> import moduleToImport
> someInstance = classToInstantiate()

Have a look at the builtin function __import__.

themodule = __import__(themodulename)
theclass = getattr(themodule, theclassname)
a = theclass()

There is a slight complication, though:
If themodulename is of the form "foo.bar", then module foo is returned. Some
themodulename.split('.'), and additional getattr calls should help.

Of course, there are all kinds of security issues with doing __import__ and
getattr like this in a CGI script...

Bjarke









More information about the Python-list mailing list