[Tutor] Import and Execute Modules in List

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon Jan 27 16:21:04 2003


On Mon, 27 Jan 2003, Sean Abrahams wrote:

> I'm developing an application where I want the user to define a list of
> modules they want to use and then the application then takes that list
> and loads those modules.
>
> As a test, I did this:
>
> ------------------------------------
> >>> a = ['cgi','Cookie','sys','re']
> >>> b = len(a)
> >>> for counter in range(b):
> ...     import a[counter]
>   File "<stdin>", line 2
>     import a[counter]
>             ^
> SyntaxError: invalid syntax
> ------------------------------------
>
> Obviously, this doesn't work, and I don't want to use an if-else
> statement.


Hi Sean,

The 'import' statement is slightly special: it doesn't take strings, but
names of the module that's going to be imported.  So we have to take a
sligthly different approach.


To do what you want is slightly trickier, but not by too much.  We can use
the builtin '__import__' function, and combine that with some globals()
fiddling.  For example:


###
[dyoo@tesuque dyoo]$ python
Python 2.2.1 (#1, Sep  3 2002, 14:52:01)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> module_names = ['random', 'unittest', 'bisect']
>>> for m in module_names:
...     globals()[m] = __import__(m)
...
>>> dir()
['__builtins__', '__doc__', '__name__', 'bisect', 'm',
 'module_names', 'random', 'unittest']
###


(By the way, I've simplified the for-loop code a little more by iterating
directly on the names of the modules, rather than their respective numeric
indices.)

For more information on those two functions --- __import__() and globals()
--- we can look at:

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-2
    http://www.python.org/doc/lib/built-in-funcs.html#l2h-24


I hope this helps!