Reject a missing module spec before import
Also published in our Blogger archive.
A module spec describes how the import system could load a module. importlib.util.find_spec() lets code ask for that description before deciding whether to import. Here, the concrete input is the intentionally nonexistent top-level name "article_fixture_missing_module_8f2c". The expected result is None, so the program asserts that result, confirms the name is absent from sys.modules, and prints that importing was skipped.
This is a useful branch for an optional, controlled dependency: call import_module() only when a spec was found. It is not a security boundary. Finders participate in discovery, and a spec's presence does not make a module trustworthy; importing a discovered module can still execute its top-level code. The test name is selected to avoid colliding with a normal standard-library module, but an environment with a custom importer could deliberately provide it. This check is also not atomic: the import environment can change between discovery and a later import.
find_spec() is available in Python 3.4 and returns None when no spec can be found. The import documentation explains that import_module() performs the actual import. See importlib.util.find_spec and importlib.import_module.
import importlib.util
import sys
missing_name = "article_fixture_missing_module_8f2c"
spec = importlib.util.find_spec(missing_name)
assert spec is None
assert missing_name not in sys.modules
print(f"spec: {spec}")
print("import skipped")
spec: None
import skipped
AI-assistance disclosure: AI helped draft this explanation and example.