Creating class instance from module and class name

Diez B. Roggisch deets at nospam.web.de
Tue Oct 6 09:57:57 CEST 2009


Steven D'Aprano schrieb:
> 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')

Not working for modules in packages, it will return the toplevel module 
only. I never remember if there is a convenience-function, what I 
usually do is this:

module = __import__(module_name)
for part in module_name.split(".")[1:]:
     module = getattr(module, part)



Diez



More information about the Python-list mailing list