Optional-dependency imports

Helpers for optional-dependency import checks.

File: klea_utils/imports.py

Copyright 2026 Ankur Sinha Author: Ankur Sinha <sanjay DOT ankur AT gmail DOT com>

klea_utils.imports.require_extra(import_names: str | list[str], extra: str, dist: str = 'klea_utils') → None[source]

Raise a helpful ImportError when optional imports are missing.

Checks each import_names entry with importlib.util.find_spec() (no module code is executed) and, if any are not findable, raises a single ImportError that tells the user how to install the Klea [extra] (pip install klea_utils[extra]). The message is extra-level only – the caller passes the import names (e.g. "bs4", not "beautifulsoup4") but the fix is the extra, which is the user-facing knob in setup.cfg.

Accepts a single import name or a list so callers can batch ["bs4", "anydoc"] into one call and get one combined hint instead of N separate try blocks.

Parameters:
  • import_names – Import name or list of import names to check (e.g. "bs4" or ["bs4", "anydoc"]).

  • extra – Extra name in setup.cfg (e.g. "mcp", "chroma").

  • dist – Distribution name that owns the extra (default "klea_utils").

Raises:

ImportError – when any of import_names is not findable.