Friday, December 03, 2010

Using Python's imp Module

There are a few modules I have not used in Python before. One of those modules is the imp - this module has been available since...well, forever in Python. But for some reason, I only recently came across it on  one of the open source projects I'm contributing to.

I had a little need to temporarily change my system path, this would have required tweaking the system import path. As it turned out, I would use the imp module which has the mechanisms for loading modules in a package dynamically just as I needed. The cool thing is that it helps most especially when the name of the module concerned isn't known.

Finding Modules:

The first step to loading a module is finding. The find_module() function scans the import search path looking for a package or module with the given name. It returns an open file handle (if appropriate for the type), filename where the module was found, and “description” (a tuple such as those returned by get_suffixes()).

import imp
from imp_get_suffixes import module_types

print 'Package:'
f, filename, description = imp.find_module('example')
print module_types[description[2]], filename

print 'Sub-module:'
f, filename, description = imp.find_module('submodule', ['./example'])
print module_types[description[2]], filename
if f: f.close()
You can learn more about Python's imp module and how to use it and many
more great modules by going to the Python Algorithms here. 

No comments:

Related Posts with Thumbnails