Extending the import mechanism - what is recommended?

dbr517 at gmail.com dbr517 at gmail.com
Tue Jan 29 08:12:46 EST 2008


I need to extend the import mechanism to support another file type.
I've already written the necessary C library to read the file and
return a python code object.

I found one example which just sub-classed imputil.ImportManager like
this:

from myLib import pye_code as pye_code
class MyImporter(imputil.ImportManager):
    def __init__(self):
        imputil.ImportManager.__init__(self)
        self.add_suffix('.pye', self.import_pye)
        self.install()

    def import_pye(self, filepath, fileinfo, filename):
        data = pye_code(filepath)
        return 0, data, {}

This actually works fine if the module is just a few lines of code,
but it won't chain to the "built-in" importers; if the module that I'm
importing does something as simple as 'import re', it fails.

It may be that my confusion here is because (even after reading the
code), I'm not clear on the purposes of imputil.ImportManager vs.
imputil.Importer :-(

What is the "preferred" way to do this type of extension?  One other
note; at this time, I just need to import individual module files with
this extension; I don't need to import packages.

Thanks!

Dan



More information about the Python-list mailing list