Neat Trick for Loading Modules with unknown Name

Ixokai usenet at ixokai.net
Sun Mar 21 23:49:26 EST 2004


*blink*

Long, complex?

>>> modname = 'email'
>>> mod = __import__(email)
>>> mod
<module 'email' from 'Z:\python23\lib\email\__init__.py'>

?

--Stephen
"Randall Smith" <randall at tnr.cc> wrote in message
news:I6t7c.80655$u_5.47815 at fe2.texas.rr.com...
> I've found an easy and clean way to load and use modules that are loaded
> after a program has started when the name of the module can not be
> pre-determined.
>
> modname = 'usermodname'
> # load the module
> exec('import ' + modname)
> # alias the module
> usersmod = eval(modname)
>
> Not you can use the module like this: usermod.def
> Where def is some function, class, etc. defined in the module.
>
> Very simple.  I stumbled on this for a while and even read some long,
> complex solutions involving using __import__, etc.  Just thought I'd
share.
>
> Randall





More information about the Python-list mailing list