[help]How to load a class dynamic?

Alex Martelli aleax at aleax.it
Tue May 13 04:38:11 EDT 2003


<posted & mailed>

dolephi9080 wrote:

> Suppose I have some 3 party Modules, and In my program, I don't know
> what is the 3 party classes are, but I can find the name from the 3
> party's Module.
> it provide a manifest, it has a line classname =
> "mypackage.mymodule.MyClass"
> now my program read this line, and how to instance the class from
> this string?

In general, you cannot, because there is no information about what
arguments you should pass for the instantiation.

But let's assume you have that information from other sources, for
example you know somehow that these classes should be instantiated
by calling them without arguments.  So, your problem basically is
reduced to getting the appropriate class object.

In turn, that class object is an attribute of a module, so your
problem reduces to getting that module.  Assuming 'mypackage' is
on your sys.path (i.e. some directory of the sys.path has a
subdirectory named 'mypackage' which contains a file __init__.py)
then __import__ can do it -- otherwise you need to find out where
the package is located, and you definitely do not have enough
info for that in your specs.

So basically we could have, just as clearly explained and
exemplified in the Python online docs at
http://www.python.org/doc/current/lib/built-in-funcs.html
(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.


Alex





More information about the Python-list mailing list