Python ModuleNotFoundError
Importing an unavailable optional exporter can raise ModuleNotFoundError. The import failure identifies which module was missing.
A simple example
ModuleNotFoundError
- Start with An optional component is absent
- Do this Try to look it up
- Result Unavailable
Syntax
import_module(name)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyLoad an optional invoice exporter
A billing application supports an optional exporter selected by class name. The workstation has only the standard installation, so the app should offer its built-in export format if the extra class is missing.
from importlib import import_module
name = "bbminfo_optional_invoice_exporter"
try:
import_module(name)
except ModuleNotFoundError as missing:
if missing.name != name:
raise
print("Use the standard export")
Use the standard export
The standalone example has no optional invoice exporter installed, so the standard format is available as a fallback.
Load the standard calendar component
The timetable editor is configured with the standard Java date class. Try to load the configured component. A missing optional class selects the fallback.
Handle an unavailable print adapter
A workstation lacks a school-specific optional adapter named in its settings. Try to load the configured component. A missing optional class selects the fallback.
What to watch for
An installed exporter might itself be missing a dependency. Check the exception's name before offering the fallback.