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

Robert Brewer fumanchu at amor.org
Mon Sep 29 15:46:26 EDT 2003


Peter Otten wrote:

> Note that all three versions will not work with submodules, e. g.
"os.path",
> so let's change it one more (last?) time:
> 
> def getClass(classname, modulename):
>     return getattr(__import__(modulename, globals(), locals(),
[classname]),
> classname)

Thanks, Peter, you finally put me on the right track with regards to
importing from packages, with that __import__ builtin. Been fighting
that for a month now, on and off. FWIW, I took your example and expanded
it into a cookbook recipe, replacing my older, much uglier solution:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223972


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list