Creating class instance from module and class name

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Oct 6 08:55:47 CEST 2009


On Mon, 05 Oct 2009 23:32:27 -0700, gentlestone wrote:

> Suppose I've saved the class name and (don't know how) I've also saved
> the Class's module (package path or I don't know what's the name for XYZ
> "from X.Y.Z import ...). How can I construct a new class according to
> saved informations? If I don't know what Class it could be, only I have
> the saved Class name?


If you have the module *object*, and the name of the class, then you can 
do this:

theclass = getattr(module, "MyClass")

to get the class itself, and then call it as normal to instantiate it:

instance = theclass(args)

Classes are just like any other object in that regard.

If you have the *name* of the module, you can import it first to get the 
module object:

module = __import__('module_name')
theclass = getattr(module, "MyClass")
instance = theclass(args)


There may be some complications if you have a dotted package name, in 
which case the docs for __import__ are your friend :)



-- 
Steven



More information about the Python-list mailing list