Add import utilities for optional dependencies (#3389)
Some checks failed
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled

This commit is contained in:
Greyson LaLonde
2025-08-24 22:57:44 -04:00
committed by GitHub
parent f96b779df5
commit c02997d956
2 changed files with 74 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
"""Import utilities for optional dependencies."""
import importlib
from types import ModuleType
class OptionalDependencyError(ImportError):
"""Exception raised when an optional dependency is not installed."""
pass
def require(name: str, *, purpose: str) -> ModuleType:
"""Import a module, raising a helpful error if it's not installed.
Args:
name: The module name to import.
purpose: Description of what requires this dependency.
Returns:
The imported module.
Raises:
OptionalDependencyError: If the module is not installed.
"""
try:
return importlib.import_module(name)
except ImportError as exc:
raise OptionalDependencyError(
f"{purpose} requires the optional dependency '{name}'.\n"
f"Install it with: uv add {name}"
) from exc