Sub topic 15
Under the hood: finders, loaders, and importlib
This chapter assumes you know the sys.modules cache and the sys.path search list from earlier chapters. Here you will see the machinery that uses both.
The two roles: finder and loader
An import statement does not search the disk itself. It delegates to two kinds of objects:
- A finder decides whether it can supply a module with a given name. If it can, it returns a spec.
- A loader takes that spec, creates the module object, and runs the module's code.
The spec is a ModuleSpec object that describes how to load the module. It is the hand-off between the two roles.
| Spec attribute | Meaning |
|---|---|
| `name` | The full dotted module name |
| `loader` | The object that will create and execute the module |
| `origin` | Where the code lives, usually a file path |
| `submodule_search_locations` | A list of directories if the module is a package, otherwise `None` |
The import flow
Python checks sys.modules first. On a cache miss, it asks each finder in sys.meta_path in order. The first finder to return a spec wins.
By default, three finders are on sys.meta_path. BuiltinImporter handles modules compiled into the interpreter. FrozenImporter handles frozen modules. PathFinder searches sys.path, which is why changing sys.path changes what you can import.
Inspecting finders and specs
import importlib.util
import sys
for finder in sys.meta_path:
print(getattr(finder, "__name__", repr(finder)))
spec = importlib.util.find_spec("json.decoder")
print(spec.name)
print(spec.origin)
print(type(spec.loader).__name__)The first loop lists the finders. Tools such as editable installs or test frameworks may add extra entries. find_spec finds a module without running its code, although for a dotted name it imports the parent package first. For json.decoder, the loader is normally SourceFileLoader, which reads a .py file.
Loading a module by hand
You can repeat the import steps yourself:
import importlib.util
spec = importlib.util.find_spec("colorsys")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
print(module.rgb_to_hsv(1, 0, 0))This prints (0.0, 1.0, 1.0). module_from_spec creates an empty module object. exec_module runs the file's code inside it.
Why this matters
ModuleNotFoundErrormeans no finder returned a spec. Runimportlib.util.find_spec(name)to check. ANoneresult confirms that nothing onsys.pathmatches.- A shadowed module shows up in
spec.origin, which points at your own file instead of the standard library. - Custom finders and loaders on
sys.meta_pathlet you import from zip archives, databases, or generated code. Most projects never need one.
Exercise
You call importlib.util.find_spec("mytool") and it returns None. Which part of the import system found nothing, and what is one thing you can check?
Show answer
Every finder on sys.meta_path failed to return a spec, so no loader was ever involved. In practice PathFinder found nothing on sys.path. Check that the module's directory is on sys.path, and that the file or package name is spelled correctly.