Python 3.1 introduced importlib, which can be used to modify the behavior of Python’s import system. In fact, standard Python imports have also been ported to use this new library.
As stated in the documentation, one of the reasons for this libraries existence is to allow programmer’s to write their own Importer modules. As one can imagine, this functionality is not widely used, however, because most people don’t have a desire to alter the functionality of standard Python importing.
However, there are definitely use cases. One blog post describes using the system to block certain modules from being imported. Further, Python has actually used the module to write an Importer that allows one to import modules from zip files. There is also a great Usenix article that describes a lot of the functionality covered in this post.
In this post, I’d like to describe how one can use pre-existing machinery, namely importlib.machinery.FileFinder to quickly write a path-based Importer module to handle custom imports.
First, some background. Importing in Python is actually pretty straight-forward (and pretty elegant). During each import statement, a list of known-importers is consulted. Each importer returns whether it can handle the module name provided. The first importer that can handle the module name is then used to load the module.
Naturally, then, each Importer has two components, a finder and a loader:
find_loader(fullname) indicates whether a module can be loaded based on its name. If the module can be loaded, the loader is returned. If not,
None is returned.
load_module(fullname) loads the module, returning the actual module and also doing some other work, such as placing it in
sys.modules. All work is described here.
The Importers are loaded from two lists,
sys.path_hooks . The former imports modules simply based on their names, while the latter imports modules based on their names within a certain path.
Using this knowledge, our goal is to then allow something like this to happen:
In the directory of our project, there is a JSON file,
records.json , which contains customer records indexed by their full name. We want to seamlessly import this file and use it as if it were a dictionary. If the file doesn’t exist, naturally, we’d like to throw an error.
import records print(records['Jane Doe'])
This seems pretty simple knowing what we know about how the Python import system works:
- Since we are operating on the FileSystem, we need to know information about paths. Therefore, we’d like to create an Importer module that can be appended to
- Our find_loader implementation should take the module name (records, in this case), append the “.json” extension to it, and then check to see if it exists on the filesystem. If it does, it should return the loader described in (3)
- Our load_module implementation should take the module name, append “.json” to it, read the contents from the filesystem, and load the JSON using Python’s
As you might notice, steps 1 and 2 are not necessarily JSON specific. In fact, they’re filesystem specific. Luckily, steps 1 and 2 have already been written and provided by Python in the form of importlib.machinery.FileFinder. We can then utilize this to write our JSON Importer.
FileFinder also has a nice helper function, FileFinder.path_hook, which allows us to specify a series of (loader, extensions) pairs. The function then returns a callable that is suitable to be inserted into
sys.path_hooks . We then only need to write the loader. The loader, by definition, is a callable that returns a Loader, which has a
load_module(fullname) method. In our implementation, we are going to utilize a class’ constructor as this callable (as suggested in PEP302). We write our loader:
import json import sys class JsonLoader(object): def __init__(self, name, path): self.path = path def load_module(self, fullname): if fullname in sys.modules: return sys.modules[fullname] with open(self.path, 'r') as f: module = json.load(f.read()) sys.modules[fullname] = module return module
Now we can use the already existing machinery to add this loader into our import system:
from importlib.machinery import FileFinder json_hook = FileFinder.path_hook( (JsonImporter, ['.json']) ) sys.path_hooks.insert(0, json_hook) # Need to invalidate the path hook's cache and force reload sys.path_importer_cache.clear() import records print(records['Jane Doe'])
And voila! We have added our new JSON importing functionality. The most important part of the above codeblock is
sys.path_importer_cache.clear() . When your code begins running, all paths checked for imports in
sys.path have already had their hook’s cached. Therefore, in order to ensure that the newly added JSON hook is processed, we need to ensure that the cached list of Importers contains the JSON hook, so we simply invalidate the cache.
The great thing about this code is that FileFinder’s path_hook handles all of the Filesystem operations for you. It automatically traverses directories if directories are part of the import statement and automatically verifies extensions. All you have to do is worry about the loading logic!
Of course, no specific-solution is a good solution. It’s also possible to generalize what we’ve done.
from importlib.machinery import FileFinder import json import sys class ExtensionImporter(object): def __init__(self, extension_list): self.extensions = extension_list def find_loader(self, name, path): self.path = path return self def load_module(self, fullname): if fullname in sys.modules: return sys.modules[fullname] return None class JsonImporter(ExtensionImporter): def __init__(self): super(JsonImporter, self).__init__(['.json']) def load_module(self, fullname): premodule = super(JsonImporter, self).load_module(fullname) if premodule is None: with open(self.path, 'r') as f: module = json.load(f) sys.modules[fullname] = module return module raise ImportError('Couldn't open path') extension_importers = [JsonImporter()] hook_list =  for importer in extension_importers: hook_list.append( (importer.find_loader, importer.extensions) ) sys.path_hooks.insert(0, FileFinder.path_hook(*hook_list)) sys.path_importer_cache.clear() import records print(records['Jane Doe'])
Now there’s no need to worry about any filesystem details. If we want a new importer based on a file extension, we simply extend the ExtensionImporter class, create a load_module method, and pop it into the extension_importers list.
And thus, a complete solution to creating custom file-extension based path-importers has been created. Two lessons I’ve learned while writing this post:
- Don’t forget to call
- For some reason, appending the finder function to the end of
sys.path_hooksdoesn’t seem to work. Inserting it at the beginning, however, does.