471,311 Members | 1,856 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,311 software developers and data experts.

Importing module with name given as a variable

What is the "best practice" for importing an arbitrary module given
that the name is stored in a variable? The context is a simple web
application with URL dispatching to a module and function. I know of
__import__(), the imp module, and exec. For each of these, is there a
way to make them work "just like" the normal import call?

Thanks,
Sean
Aug 30 '08 #1
1 1067
On Sat, 30 Aug 2008 11:02:03 -0700 (PDT), Sean Davis wrote:
What is the "best practice" for importing an arbitrary module given
that the name is stored in a variable? The context is a simple web
application with URL dispatching to a module and function. I know of
__import__(), the imp module, and exec. For each of these, is there a
way to make them work "just like" the normal import call?
It all depends on your needs. If you have to deal with user
input to get the name of the module, better use __import__
than exec. __import__ works just like the normal import call:

import sys

is equal to:

sys = __import__('sys')

If you need, let's say, to search for a module that lies
outside sys.module paths, then use imp's functions.

HTH.

--
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
Aug 30 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Jason Charalambides | last post: by
12 posts views Thread by qwweeeit | last post: by
4 posts views Thread by jean-marc | last post: by
5 posts views Thread by dixie | last post: by
30 posts views Thread by Franck PEREZ | last post: by
reply views Thread by Pradnyesh Sawant | last post: by
reply views Thread by norseman | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.