Python Import Hooks: Customizing import with Finders and Loaders
This article explains the stages of a Python import, builds a finder and a loader that serve modules and packages from a dictionary, and identifies the risks of extending a mechanism on which every module depends.
The statement import looks simple, but it runs a small protocol: Python consults a cache of loaded modules, asks a list of finders whether any of them can locate the requested name, and hands the result to a loader that creates and executes the module. Each of these steps is an ordinary Python object that a program can inspect or extend, which is why modules can be imported from ZIP archives, from frozen executables or from any other source. The present article examines the stages of an import, builds a finder and a loader that serve modules from a dictionary, extends them to packages, and identifies the risks of changing a mechanism on which every other module depends. A hook placed in the import system, used sparingly, is the secret weapon that lets Python load code from places it did not originally know.
The Stages of an Import
An import first checks sys.modules, the dictionary of modules already loaded; only when the name is missing does it walk the list sys.meta_path, calling the method find_spec of each finder until one returns a module spec instead of None. The following example shows both structures.
import sys
print([getattr(f, "__name__", type(f).__name__) for f in sys.meta_path])
# Output: ['BuiltinImporter', 'FrozenImporter', 'PathFinder']
import json
print("json" in sys.modules) # Output: True
print(json.__spec__.name, json.__spec__.loader is not None) # Output: json True
import json as again
print(again is json) # Output: True
The three default finders locate built-in modules compiled into the interpreter, frozen modules, and modules found along sys.path; the last one, PathFinder, delegates in turn to the hooks of sys.path_hooks, which is how ZIP archives listed in sys.path are imported without any custom code. The second import of json returns the same object without consulting any finder, because the module is already in the cache. Every module records the spec that produced it in __spec__.
A Finder and a Loader for Virtual Modules
Since Python 3.4 (PEP 451), a finder returns a ModuleSpec, and a loader provides two methods: create_module, which may return None to accept the default module object, and exec_module, which fills the module. In the words of a certain starship captain, "Make it so": the finder prepares the plan, and the loader carries it out. A single class can play both roles, as the following example shows with modules stored as source strings in a dictionary.
import sys
from importlib.abc import Loader, MetaPathFinder
from importlib.util import spec_from_loader
SOURCES = {
"greeting": 'MESSAGE = "hello from a dictionary"\ndef shout():\n return MESSAGE.upper()',
}
class DictImporter(MetaPathFinder, Loader):
def __init__(self, sources):
self.sources = sources
self.lookups = 0
def find_spec(self, fullname, path, target=None):
if fullname not in self.sources:
return None # Let the next finder try.
self.lookups += 1
return spec_from_loader(fullname, self, origin=f"<dict:{fullname}>")
def create_module(self, spec):
return None # Use the default module object.
def exec_module(self, module):
code = compile(self.sources[module.__name__], module.__spec__.origin, "exec")
exec(code, module.__dict__)
importer = DictImporter(SOURCES)
sys.meta_path.insert(0, importer)
import greeting
import greeting as same
print(greeting.shout()) # Output: HELLO FROM A DICTIONARY
print(greeting.__spec__.origin) # Output: <dict:greeting>
print(importer.lookups) # Output: 1
sys.meta_path.remove(importer)
The finder answers only for names it knows and returns None for every other one, so the rest of the import system keeps working. The source is compiled with compile before execution, which gives tracebacks a meaningful file name and produces the code object described in the article devoted to bytecode. The counter confirms that the second import came from sys.modules. The finder is inserted at the front of sys.meta_path so that it is consulted first, and it is removed in place with remove once it is no longer needed.
Packages and Failed Imports
A package is a module with a __path__, which tells the import system to look for submodules. A spec declares it by passing is_package=True, and the submodule is then requested with its full dotted name. The same example shows what happens when the module code raises an exception.
import sys
from importlib.abc import Loader, MetaPathFinder
from importlib.util import spec_from_loader
SOURCES = {
"settings": "",
"settings.database": 'URL = "sqlite:///app.db"',
"broken": "raise RuntimeError('cannot initialize')",
}
PACKAGES = {"settings"}
class DictImporter(MetaPathFinder, Loader):
def find_spec(self, fullname, path, target=None):
if fullname not in SOURCES:
return None
return spec_from_loader(fullname, self, is_package=fullname in PACKAGES)
def create_module(self, spec):
return None
def exec_module(self, module):
exec(SOURCES[module.__name__], module.__dict__)
sys.meta_path.insert(0, DictImporter())
import settings.database
print(settings.database.URL) # Output: sqlite:///app.db
print(settings.__path__) # Output: []
try:
import broken
except RuntimeError as error:
print(error, "broken" in sys.modules) # Output: cannot initialize False
try:
import missing_module
except ModuleNotFoundError as error:
print(error) # Output: No module named 'missing_module'
The import of settings.database first imports the package settings and then the submodule, whose fully qualified name reaches the finder. The module is placed in sys.modules before its code runs, so that circular imports can find it, and it is removed again when that code fails, which allows a later import to retry. A name that no finder claims ends in ModuleNotFoundError, the subclass of ImportError raised when nothing is found.
Pitfalls of Import Hooks
A finder participates in every import of the program, including those of the standard library and of third-party packages. Five pitfalls are distinguished, which are the following:
- Shadowing. A finder placed first that answers for a name used elsewhere, such as
jsonorlogging, replaces that module for the whole program. - The cache hides changes. Once a module is in
sys.modules, its finder is never asked again; reloading requiresimportlib.reloador removing the entry. - Removed APIs.
find_modulewas replaced byfind_specin Python 3.4 and removed in Python 3.12, andload_modulehas been deprecated since 3.4 with removal announced for Python 3.15; old tutorials still use both. - Executing untrusted code. A loader that executes source from a database or a network endpoint runs that code with the full privileges of the program.
- Global state in tests. A hook left in
sys.meta_path, or a module left insys.modules, leaks into later tests; installing the hook in a context manager, as described in the article devoted to context managers, guarantees its removal.
The second pitfall is also the reason why replacing a module in tests is usually done by patching sys.modules or the attribute that the code reads, as examined in the article devoted to monkey patching, rather than by installing a finder.
Choosing the Right Mechanism
Consequently, a custom finder is justified only when modules come from a source that the default finders cannot read, as the following table summarizes.
| Need | Recommended mechanism |
|---|---|
| Import a module whose name is known only at runtime | importlib.import_module(name) |
| Load a module from a specific file path | importlib.util.spec_from_file_location with module_from_spec |
| Import from a ZIP archive | Add the archive to sys.path; zipimport handles it |
| Modules stored in a database, in memory or generated on the fly | A meta path finder and loader, as in this article |
Support a new kind of sys.path entry |
A path entry finder registered in sys.path_hooks |
| Replace a module in tests | Patch sys.modules or the attribute used by the code |
Conclusion
It is concluded that the import system is a short pipeline of replaceable objects: a cache in sys.modules, a list of finders in sys.meta_path, and loaders that create and execute modules from the specs those finders return. A finder and loader of a few lines are enough to import modules from a dictionary, including packages, and the same protocol underlies ZIP imports and frozen applications. This magic reaches every import of the program, so a hook must answer only for its own names, be removed when it is no longer needed, and never execute code from an untrusted source. A loader that compiles source code can also transform it before execution; abstract syntax trees, the representation in which such transformations are written, are developed in a future article of this series.