2006-09-27

Another way to bootstrap alternative importers

I just realized another way to bootstrap alternative importers into Python when your package or module needs it using Python as it stands now. All you need is for your alternative importer to have the code to add it to 'sys' executed at import time (so adding itself to sys.path_hooks or sys.meta_path and clearing sys.path_importer_cache) and to have a .pth file that imports the alternative importer.

While the resolution of .pth files is the last step in terms of playing with sys.path in 'site', it is the second import to happen after zipimport and the first that is not a built-in module. This means that it should do its .pth file handling before you need any alternative importer to be available for your code.

Obviously the other option is to have a .pth file or something similar just for alternative importers that is handled as early as possible.

Oh, and I realized another reason to have a single .pth file for a Python interpreter; deterministic interpretation based on something other than file name. As it stands now .pth files are handled first in the order of the directories in sys.path, and then based on file name of the .pth files. If a single file was appended or deleted from the exact order could be more easily controlled. It wouldn't be required that you rename anything that had a funky order requirement.

This could even allow for import statements for alternative importers to be in the same .pth file. Just put them first and then list what you need after. The other option is that if your added path in the .pth file needs an alternative importer you just make sure that import statement for the alternative importer happens before you add your entries to sys.path. If subsequent entries are made in the .pth file that also require the same alternative importer it is a no-op for getting the alternative importer installed since import will not re-execute the importation of your alternative importer. Simple! =)