Loading a class the name of which is only known runtime

Mads Orbesen Troest mads at troest.NEVERMORE.dk
Tue Apr 8 15:11:31 EDT 2003


On Tue, 8 Apr 2003 21:01:56 +0200, Bjarke Dahl Ebert wrote:

Hi Bjarke;

> Have a look at the builtin function __import__.
> themodule = __import__(themodulename)
> theclass = getattr(themodule, theclassname)
> a = theclass()

Thanks for your suggestion, this seems like just what I am after!

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

Well, you're right of course, but I actually don't plan to allow arbitrary 
imports from the CGI parameter (although I know my post to Tim suggested 
that). What I am doing is having a central python script registered as 
handler for some file extensions in Apache, and I have pages implemented as 
python classes. What I want to do is for the central python handler to 
"dispatch" the page (class) given as argument. Now, if I restrict all these 
page objects to reside in a fixed package, and only allow for import of 
that package, I should think that the security issue (arbitraty module 
import) goes away, as only page-objects inside the page-package can be 
specified.

At any rate, thank you very much for your feedback!

Regards,
   /\/\\ads Orbesen Troest




More information about the Python-list mailing list