Library contents

Python ModuleNotFoundError

Importing an unavailable optional exporter can raise ModuleNotFoundError. The import failure identifies which module was missing.

A simple example

ModuleNotFoundError

  1. Start with An optional component is absent
  2. Do this Try to look it up
  3. Result Unavailable
Detecting the missing component lets the program choose a built-in alternative.

Syntax

Python 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.py

Load 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 the programname = "bbminfo_optional_invoice_exporter"
ResultUse the standard export
lesson.py
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")
Output
Use the standard export

The standalone example has no optional invoice exporter installed, so the standard format is available as a fallback.

Advertisements

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.

Givenjava.time.LocalDate
Worked resultComponent available

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.

Givenschool.example.OptionalPrinter
Worked resultUse fallback

What to watch for

An installed exporter might itself be missing a dependency. Check the exception's name before offering the fallback.

Documentation for ModuleNotFoundError