How to instatiate a class of which the name is only known at runtime?
Chad Netzer
cnetzer at sonic.net
Tue Sep 9 16:35:37 EDT 2003
On Tue, 2003-09-09 at 12:45, Nick Welch wrote:
> > 2. How to write such code to instantiate?
>
> class = getattr(modulename, classname)
> or
> class = globals()[classname]
"class" is a keyword, and so the above won't work, but the idea is
sound. (Just use a different identifier than 'class')
> and then:
>
> an_instance = class()
>
> Although this all seems really dirty to me. Maybe there are better ways
> to do it.
The first form, using getattr, is perfectly idiomatic, and that is what
I use.
Also, regarding the earlier import question, there is the builtin
__import__ function:
help(__import__)
--
Chad Netzer
More information about the Python-list
mailing list