imports
Optional dependency detection, lazy imports, and availability flags.
Functions:
-
package_availableβCheck if a package is available in your environment.
-
module_availableβCheck if a module path is available in your environment.
-
check_requirementβCheck if a package with specified version is available.
-
optional_importβImport a module lazily and return a boolean indicating availability.
check_requirement cached [source] ΒΆ
Check if a package with specified version is available.
Parameters:
-
requirement(str) βPackage with optional version requirement (e.g., "torch>=1.10.0")
Returns:
-
boolβBoolean indicating if the requirement is satisfied
Examples:
optional_import cached [source] ΒΆ
optional_import(
module_path: str,
name: str = "",
requirement: str = "",
url: Optional[str] = None,
) -> Tuple[Any, bool]
Import a module lazily and return a boolean indicating availability.
When the top-level package is installed and no requirement is given, the returned object is a lightweight proxy that defers the actual import to first use (attribute access, call, isinstance check, or subclassing), so module-scope calls do not load heavy dependencies at import time. With a requirement, the module is imported eagerly to check its version. When the dependency is missing, the returned proxy raises an informative ImportError on any use.
The (module, available) return contract and the raising placeholder for missing dependencies are modeled on MONAI's optional_import (https://github.com/Project-MONAI/MONAI/blob/1.4.0/monai/utils/module.py#L283).
Parameters:
-
module_path(str) βPath to the module to import (e.g.
torch) -
name(str, default:'') βName of the class, function or attribute to import from the module (e.g.
from torch import nn, heremodule="torch", name="nn") -
requirement(str, default:'') βRequirement for the module (e.g., ">=1.10.0")
-
url(Optional[str], default:None) βURL of the module documentation, if any. Will be used in case of an import error.
Returns:
-
Tuple[Any, bool]βImported module (or proxy) and boolean indicating availability
Examples:
>>> torch, IS_TORCH_AVAILABLE = optional_import("torch", requirement=">=2.5.0")
>>> IS_TORCH_AVAILABLE
True
>>> pkg, IS_PKG_AVAILABLE = optional_import("missing_package")
>>> IS_PKG_AVAILABLE
False
>>> pkg.some_function() # doctest: +SKIP
ImportError: Optional module 'missing_package' is not installed.