Optional import
optional_import
#
Functions:
Name | Description |
---|---|
optional_import |
Attempt to import an optional module and handle its absence gracefully. |
optional_import
#
optional_import(
module_name: str, raise_error: bool = False
) -> typing.Tuple[typing.Any, bool]
Attempt to import an optional module and handle its absence gracefully.
This function is useful when you want to provide optional features that depend on modules that may not be installed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
Name of the module to import (e.g., 'numpy', 'torch'). |
required |
|
bool
|
If True, raise an OptionalImportError when the module is not found. If False, return (None, False) when import fails. |
False
|
Returns:
Type | Description |
---|---|
tuple
|
A tuple containing (module, success_flag), where: - module: The imported module if successful, None if failed - success_flag: True if import succeeded, False otherwise |
Examples:
>>> # Basic usage - silent failure
>>> numpy, has_numpy = optional_import("numpy")
>>> if not has_numpy:
... raise OptionalImportError("numpy")
>>> # Usage with error raising
>>> torch, _ = optional_import(
... "torch", raise_error=True
... )
>>> # Will raise OptionalImportError if torch is not installed