[help]How to load a class dynamic?

Alex Martelli aleax at aleax.it
Wed May 14 04:14:55 EDT 2003


<posted & mailed>

dolephi9080 wrote:
   ...
>> > it provide a manifest, it has a line classname =
>> > "mypackage.mymodule.MyClass"
>> > now my program read this line, and how to instance the class
   ...
>> http://www.python.org/doc/current/lib/built-in-funcs.html"]http-
>> ://www.python.org/doc/current/lib/built-in-funcs.html[/url]
>> (just prettied up a bit...):
>>
>> def my_import(structured_name):
>>     mod = __import__(structured_name)
>>     component_names = structured_name.split('.')
>>     for component_name in component_names[1:]:
>>         mod = getattr(mod, component_name)
>>     return mod
>>
>> Now, my_import('mypackage.mymodule.MyClass') should give you
>> the class object as the result.  Therefore,
>>
>> my_instance = my_import('mypackage.mymodule.MyClass')()
>>
>> [note the empty trailing parentheses to mean 'call without
>> arguments'] should build and give you the instance you want,
>> under the set of assumptions listed throughout this post.
> 
> It seems not work, I try it. it return a Module Object not class, so it
> will tell you no module. it's main function is import Module not class

Ah yes, sorry, you do need to remove the last component of the
structured name, obviously.  So the function you need is actually:

def my_import(structured_name):
    component_names = structured_name.split('.')
    mod = __import__('.'.join(component_names[:-1]))
    for component_name in component_names[1:]:
        mod = getattr(mod, component_name)
    return mod

Better?


Alex





More information about the Python-list mailing list