Re[2]: [Tutor] Import and Execute Modules in List

Sean Abrahams Sean Abrahams <sa@sfsu.edu>
Mon Jan 27 16:43:01 2003


Danny,

Pefect =). Thank you!

--Sean

Monday, January 27, 2003, 1:20:33 PM, you wrote:



DY> 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.


DY> Hi Sean,

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


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


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


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

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

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


DY> I hope this helps!


DY> _______________________________________________
DY> Tutor maillist  -  Tutor@python.org
DY> http://mail.python.org/mailman/listinfo/tutor