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

John Roth newsgroups at jhrothjr.com
Tue Sep 9 22:16:45 CEST 2003


"Marco Herrn" <herrn at gmx.net> wrote in message
news:mailman.1063135996.15871.python-list at python.org...
> Hi,
>
> 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.

As Nick said, you can use the exec statement. You can
also use the _import() function.

> 2. How to write such code to instantiate?
>
> The first is a problem, when I don't know where the classes reside.

I'm not sure what you mean by this. Modules exist on disk in
a directory. There may be more than one class in a module,
and there is no way of automatically asking for a class and
having the module containing that class loaded.

> Currently it is planned that all these classes reside in a specific
> subdirectory. Is it possible to say 'import * from subdirectory' ?

No. It is possible to load the names of all the modules in the
subdirectory, though. That doesn't tell you what classes are in
each module unless you either establish some standards or use
a configuration file of some kind.

You could, of course, simply import all of the modules, and then
loop through them looking for the classes.

> What other problems could occur here and how could I avoid them?

The biggest problem I can see is name collisions, and that's only
a problem if you don't establish standards, and use the simplest
method, which is to use the identifier that the import statement
adds to the module.

> And to the second question, I have no idea about how to do this. Any
> hints?

As Nick points out, the easiest way is simply to build an import
statement, and then exec it.

John Roth
>
>
> Bye
> Marco
>
> -- 
> You can't judge a book by the way it wears its hair.
>
> --
> Marco Herrn             herrn at gmx.net
> (GnuPG/PGP-signed and crypted mail preferred)
> Key ID: 0x94620736
>






More information about the Python-list mailing list