Dynamic loading of modules

Alex Martelli aleax at aleax.it
Tue Sep 24 08:42:47 EDT 2002


Johan Fredrik Øhman wrote:

> I tried this below.  But as you see, even if the Password.py has a "def
> init()" it doesn't work.
> 
> Python 2.2 (#1, Mar 26 2002, 15:46:04)
> [GCC 2.95.3 20010315 (SuSE)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> z = __import__("plugins.Password")
>>>> z.init()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'module' object has no attribute 'init'

__import__ returns the TOP-LEVEL module in the package even when you
import a dotted name.  SO, you need:

x = __import__('plugins.Password')
x = getattr(x, 'Password')

and now you should have the effect you want.

x = x.Password

would be OK too instead of the getattr call, of course, but the
latter has the advantage that you can use a variable to hold
the attribute (submodule) name:-).


Alex




More information about the Python-list mailing list