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

Nick Welch mack at incise.org
Tue Sep 9 15:45:08 EDT 2003


On Tue, Sep 09, 2003 at 09:35:30PM +0200, Marco Herrn wrote:
> I am writing a program that has to instantiate a class from which I
> don't know the name until runtime. That leads to two problems for me.
> 
> 1. How to do the import? I didn't find a way to give a string to the
>    import statement.

exec("import %s" % modulename) ?

> 2. How to write such code to instantiate?

class = getattr(modulename, classname)
or
class = globals()[classname]

and then:

an_instance = class()

Although this all seems really dirty to me.  Maybe there are better ways
to do it.

> Is it possible to say 'import * from subdirectory' ?

If the directory is a python package (has an __init__.py), then you can
do 'from directoryname import *'

-- 
Nick Welch aka mackstann | mack @ incise.org | http://incise.org
The one good thing about repeating your mistakes is that you know when
to cringe.





More information about the Python-list mailing list