You are here: Home > Dive Into Python > Functional Programming > Dynamically importing modules | << >> | ||||
Dive Into PythonPython from novice to pro |
OK, enough philosophizing. Let's talk about dynamically importing modules.
First, let's look at how you normally import modules. The import module syntax looks in the search path for the named module and imports it by name. You can even import multiple modules at once this way, with a comma-separated list. You did this on the very first line of this chapter's script.
Now let's do the same thing, but with dynamic imports.
>>> sys = __import__('sys') >>> os = __import__('os') >>> re = __import__('re') >>> unittest = __import__('unittest') >>> sys >>> <module 'sys' (built-in)> >>> os >>> <module 'os' from '/usr/local/lib/python2.2/os.pyc'>
So __import__ imports a module, but takes a string argument to do it. In this case the module you imported was just a hard-coded string, but it could just as easily be a variable, or the result of a function call. And the variable that you assign the module to doesn't need to match the module name, either. You could import a series of modules and assign them to a list.
>>> moduleNames = ['sys', 'os', 're', 'unittest'] >>> moduleNames ['sys', 'os', 're', 'unittest'] >>> modules = map(__import__, moduleNames) >>> modules [<module 'sys' (built-in)>, <module 'os' from 'c:\Python22\lib\os.pyc'>, <module 're' from 'c:\Python22\lib\re.pyc'>, <module 'unittest' from 'c:\Python22\lib\unittest.pyc'>] >>> modules[0].version '2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)]' >>> import sys >>> sys.version '2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)]'
Now you should be able to put this all together and figure out what most of this chapter's code sample is doing.
<< Data-centric programming |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
Putting it all together >> |