Importing module with name given as a variable

Wojtek Walczak gminick at bzt.bzt
Sat Aug 30 15:10:43 EDT 2008


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/



More information about the Python-list mailing list