Separate Finders from Loaders
Core idea
Import first checks sys.modules. A finder on sys.meta_path can return a ModuleSpec or None; a loader can create a module and execute its initialization. module_from_spec creates an object from a spec, but exec_module performs initialization. The ordinary import machinery also manages caching and cleanup.
from importlib.machinery import BuiltinImporterspec = BuiltinImporter.find_spec('sys')print(spec.name)print(BuiltinImporter.find_spec('email') is None)This finder handles built-in modules, not every importable name.
Create then initialize
from importlib.abc import Loaderfrom importlib.util import spec_from_loader, module_from_specclass LabelLoader(Loader): def exec_module(self, module): module.label = 'ready'spec = spec_from_loader('lesson_label', LabelLoader())module = module_from_spec(spec)print(hasattr(module, 'label'))spec.loader.exec_module(module)print(module.label)The attribute appears only during execution. This manual sequence is not a complete import implementation.
Common mistake
A finder returning None allows other finders to try; raising an exception generally aborts resolution. Do not call exec_module on arbitrary loaders just to inspect them.
Practice
Add a second fixed attribute in LabelLoader and verify it is absent before initialization. Explain where normal imports cache the module.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Finders and loaders
Check your understanding of finders and loaders.
What is printed?
import sysimport mathprint(sys.modules['math'] is math)What is printed?
from importlib.machinery import BuiltinImporterprint(BuiltinImporter.find_spec('sys') is None)What is a finder’s result on no match?
Which method initializes a module?