By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,548 Members | 1,550 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,548 IT Pros & Developers. It's quick & easy.

Neat Trick for Loading Modules with unknown Name

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
*blink*

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

?

--Stephen
"Randall Smith" <ra*****@tnr.cc> wrote in message
news:I6*******************@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

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.