[Python-Dev] New and Improved Import Hooks

Fredrik Lundh fredrik@pythonware.com
Thu, 5 Dec 2002 14:33:57 +0100


Guido wrote:

> Obviously if the data files get stored in the zip file too, the code
> searching for it needs to be made zip file aware; but if zip files are
> used to provide *other* libraries, that shouldn't break code that
> looks for data files along sys.path.

as I might have mentioned before, it would be really nice if custom
importers supported optional "load_data" and "get_module_names"
hooks.

the former can be used by code that looks for data files on the path
(Zope, PIL, most likely hundreds of other tools/programs):

    for path in sys.path:
        if hasattr(path, "load_data"):
            try:
                data =3D path.load_data(name)
            except IOError:
                pass
            else:
                return data # got it
        if isinstance(path, types.StringTypes) and os.path.isdir(path):
            try:
                data =3D open(os.path.join(path, file)
            except IOError:
                pass
            else:
                return data
        # ...

the latter can be used by code that looks for plugins using a
name pattern (PIL's *ImagePlugins, for example):

    for path in sys.path:
        if hasattr(path, "get_module_names"):
            names =3D path.get_module_names()
        elif isinstance(path, types.StringTypes) and =
os.path.isdir(path):
            names =3D os.listdir(path)
        else:
            continue
        for name in names:
            if name.endswith("ImagePlugin"):
                __import__(name)

(stupid idea: why not change os.path.isdir to return False for non-
string arguments?  it's a predicate function, after all...)

</F>