Sub topic 15
Under the hood: finders, loaders, and importlib
This chapter assumes you know the import forms, the sys.modules cache, and sys.path from earlier chapters. Here you will see the machinery behind import x. You will learn to inspect it, extend it, and use it to debug import problems.
The import protocol in one pass
When you run import pkg.mod, Python calls importlib.__import__. For each dotted name (pkg, then pkg.mod) it does the following:
- It looks the full name up in
sys.modules. If it finds an entry, the import is done. - If not, it asks each object in
sys.meta_path, in order, to find the module. These objects are called finders. A finder is an object with afind_spec(fullname, path, target)method. - The first finder that returns something other than
Nonehas found the module. What it returns is a module spec (importlib.machinery.ModuleSpec). The spec records the module's name, where it lives, and which loader can run it. - Python creates an empty module object from the spec and stores it in
sys.modules. - The spec's loader runs the module's code inside that module object. A loader is an object with
create_module(spec)andexec_module(module)methods. - If every finder returns
None, Python raisesModuleNotFoundError.
Step 4 happens before step 5. The module is already in sys.modules while its code runs. This is why a partly initialized module can be seen by a circular import. It is also why a failed import must remove the half-built module from the cache.
Inspecting finders and specs
You can look at the machinery directly.
import sys
import importlib.util
for finder in sys.meta_path:
print(finder)
spec = importlib.util.find_spec("json")
print(spec.name)
print(spec.origin)
print(spec.loader)
print(spec.parent)
print(spec.submodule_search_locations)A standard interpreter lists at least three finders:
| Finder | What it finds |
|---|---|
| `BuiltinImporter` | Modules compiled into the interpreter, such as `sys` |
| `FrozenImporter` | Modules frozen into the interpreter, such as parts of the import system itself |
| `PathFinder` | Everything found through `sys.path`, which covers almost all of your code |
Tools may add more. Editable installs, pytest's assertion rewriting, and coverage tools can all put extra finders on sys.meta_path.
The fields of a spec matter when you debug:
| Field | Meaning |
|---|---|
| `name` | The full dotted name |
| `loader` | The object that will execute the code |
| `origin` | Usually the file path, or a label such as `built-in` |
| `submodule_search_locations` | A list for packages, `None` for plain modules |
| `parent` | The containing package name |
| `cached` | Where the compiled `.pyc` file lives, if any |
find_spec returns None when the module cannot be found. It does not raise. That makes it a safe way to test whether an optional dependency is installed without importing it.
import importlib.util
if importlib.util.find_spec("numpy") is None:
print("numpy is not installed")For a dotted name such as "os.path", find_spec imports the parent package first. Importing the parent runs its code, so the check is not free of side effects.
How PathFinder uses sys.path
PathFinder does not scan directories itself. For each entry in sys.path it needs a path entry finder. It looks one up in sys.path_importer_cache. On a miss, it tries each callable in sys.path_hooks until one accepts the entry. The standard hook builds a FileFinder for a directory.
A FileFinder caches its directory listing. If your program creates a new .py file after the directory was first searched, the import may not see it. Call importlib.invalidate_caches() after creating modules at run time.
import importlib
import sys
from pathlib import Path
Path("late_module.py").write_text("X = 1\n")
importlib.invalidate_caches()
sys.path.insert(0, ".")
import late_module
print(late_module.X)Writing a custom finder and loader
A finder and a loader are small. The example below serves modules from a dictionary of source strings.
import sys
import importlib.abc
import importlib.util
SOURCES = {
"greeting": "MESSAGE = 'hello from memory'\n\ndef shout():\n return MESSAGE.upper()\n",
}
class DictLoader(importlib.abc.Loader):
def create_module(self, spec):
return None # use Python's default module object
def exec_module(self, module):
name = module.__spec__.name
code = compile(SOURCES[name], f"<memory:{name}>", "exec")
exec(code, module.__dict__)
class DictFinder(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
if fullname in SOURCES:
return importlib.util.spec_from_loader(fullname, DictLoader())
return None # let the next finder try
sys.meta_path.append(DictFinder())
import greeting
print(greeting.shout())
print(greeting.__spec__.loader)Three details in this code matter:
create_modulereturnsNoneto ask Python for a normal empty module. Return your own object only when you need a special module type.exec_modulefillsmodule.__dict__. It does not return the module.find_specreturnsNonefor names it does not own. Raising an exception would stop the whole search.
The position in sys.meta_path decides priority. With append, PathFinder runs first, so a file named greeting.py on sys.path would win. Use sys.meta_path.insert(0, ...) to override normal lookup. That is powerful and risky, because your finder then sees every import.
Loading a file by path
Sometimes you have a file that is not on sys.path, such as a user-supplied plugin. The standard recipe uses spec_from_file_location.
import importlib.util
import sys
from pathlib import Path
def load_from_path(name, path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
try:
spec.loader.exec_module(module)
except BaseException:
del sys.modules[name]
raise
return module
Path("plugin_demo.py").write_text("VALUE = 42\n")
plugin = load_from_path("plugin_demo", "plugin_demo.py")
print(plugin.VALUE)The order mirrors what the import system does. It builds the module, registers it in sys.modules, and then executes it. Registering first lets the module import itself by name, for example in a dataclass or pickle round trip. Removing the entry on failure matches the standard behavior, so a broken module is not left in the cache.
Reloading and its limits
importlib.reload(module) finds the module's spec again and re-executes the code inside the same module object. Three consequences follow:
- Names defined in the old version stay in the module's namespace unless the new code overwrites them.
- Other modules that did
from mod import funcstill hold the old function. Onlymod.funcsees the new one. - Existing instances keep the old class, so
isinstancechecks against the new class fail.
Treat reload as a development convenience. Do not use it as a deployment mechanism.
Debugging checklist
- Run
importlib.util.find_spec("name"). ANoneresult means no finder found it. Checksys.path. - If a spec is found, read
spec.origin. A surprising path usually means a shadowing file. - Run
python -v -c "import name"to trace each lookup and each file that is loaded. - Print
sys.meta_pathwhen imports behave oddly. A third-party finder may be changing the result. - Inspect
sys.modules.get("name"). A stale or partly built entry explains many "attribute missing" errors.
Exercise
Your custom finder is appended to sys.meta_path. A file tools.py exists on sys.path, and your finder also claims the name tools. Which one does import tools use, and how do you make your finder win?
Show answer
The file wins, because PathFinder comes earlier in sys.meta_path and returns a spec first. To make your finder win, insert it at the front with sys.meta_path.insert(0, DictFinder()). It must also return None for every name it does not own, so other imports are unaffected.
Exercise
In load_from_path, what goes wrong if you call spec.loader.exec_module(module) before setting sys.modules[name] = module, and the module's code runs import plugin_demo?
Show answer
The module is not in sys.modules yet, so the inner import starts a second, separate import of the same name. Python runs the file again to build a different module object, which can cause duplicate side effects or infinite recursion. Registering the module first lets the inner import find the half-built module in the cache.