Entry
How can I create an object at runtime, giving its module and class name?
May 11th, 2000 07:27
unknown unknown, Fred Gansevles, Courageous, Martin Valiente
The simpelest way, without having to figure out which part of the
"stringWithFullNameOfTheClass" is the module and which part is the class
is to pass them both to a function, i.e.
def classFromModule (module, className):
mod = __import__ (module)
return getattr (mod, className)
You can use this as follows:
c = classFromModule (ModuleOfTheClass, NameOfTheClass)
o = c ()
or, even:
o = classFromModule (ModuleOfTheClass, NameOfTheClass)()
-- Instructive Comment -- (Courageous wrote)
A partial answer, without the module capability, using a different
solution than above:
o=eval(className)()
In the other language that I'm familiar with, "eval" is expensive, so
I'm pretty sure the other poster's answer is better. This is here for
instructive purposes. Python eval() can be used to interpret any valid
python expression which is currently in the form of a string. You
probably should only make very judicious use of this function, but
still...