Scope Import Hook Customization
Core idea
A meta path hook is a finder registered in sys.meta_path. It can select a loader for a specific name. Hooks change process-wide resolution; keep their namespace narrow, do not shadow existing modules, restore the original state and avoid untrusted loaders. Cached names bypass ordinary finder lookup.
from importlib.abc import MetaPathFinderclass DemoFinder(MetaPathFinder): def find_spec(self, fullname, path=None, target=None): return Nonefinder = DemoFinder()print(finder.find_spec('math') is None)This finder declines all names; the other finders can continue.
Install and remove a fixed hook
import sys, importlibfrom importlib.abc import MetaPathFinder, Loaderfrom importlib.util import spec_from_loadername = '_bytemind_lesson93_demo'class LoaderDemo(Loader): def exec_module(self, module): module.value = 7class FinderDemo(MetaPathFinder): def find_spec(self, fullname, path=None, target=None): if fullname == name: return spec_from_loader(fullname, LoaderDemo())finder = FinderDemo()assert name not in sys.modulessys.meta_path.insert(0, finder)try: print(importlib.import_module(name).value)finally: sys.meta_path.remove(finder) sys.modules.pop(name, None)print(finder not in sys.meta_path)Only a synthetic name is served. Both hook and cached module are removed in finally.
Common mistake
Changing sys.meta_path affects other imports, including concurrent ones. This single-threaded teaching example is not a production plugin isolation mechanism. Prefer explicit registration when possible.
Practice
Trace the fixed hook and explain why a second import before cleanup would reuse the cached module. Do not install hooks for external package names.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Import hooks
Check your understanding of import hooks.
What is printed?
import sysprint(isinstance(sys.meta_path, list))What is printed?
import importlib, sysprint(importlib.import_module('sys') is sys)What should a narrow finder do for unrelated names?
Why remove both synthetic cache and hook?