64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
# Copyright 2025-present the zvec project
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
from typing import Any, Optional
|
|
|
|
|
|
def require_module(module: str, mitigation: Optional[str] = None) -> Any:
|
|
"""Import a Python module and raise a user-friendly error if it is not available.
|
|
|
|
This utility helps provide actionable error messages when optional dependencies
|
|
are missing. It attempts to import the given module and, on failure, suggests
|
|
a `pip install` command based on either the module name or an optional
|
|
mitigation package name.
|
|
|
|
Args:
|
|
module (str): The full module name to import (e.g., ``"numpy"``, ``"pandas.io.parquet"``).
|
|
mitigation (Optional[str], optional): The package name to suggest for installation
|
|
if the import fails. If not provided, the top-level package of `module`
|
|
will be used (e.g., ``"pandas"`` for ``"pandas.io.parquet"``).
|
|
|
|
Returns:
|
|
Any: The imported module object.
|
|
|
|
Raises:
|
|
ImportError: If the module cannot be imported, with a clear installation hint.
|
|
|
|
Examples:
|
|
>>> import zvec
|
|
>>> np = zvec.require_module("numpy")
|
|
>>> pq = zvec.require_module("pyarrow.parquet", mitigation="pyarrow")
|
|
|
|
Note:
|
|
This function is intended for lazy-loading optional dependencies
|
|
with helpful error messages, not for core dependencies.
|
|
"""
|
|
try:
|
|
return importlib.import_module(module)
|
|
except ImportError as e:
|
|
package = mitigation or module
|
|
msg = f"Required package '{package}' is not installed. "
|
|
if "." in module:
|
|
top_level = module.split(".", maxsplit=1)[0]
|
|
msg += f"Module '{module}' is part of '{top_level}', "
|
|
if mitigation:
|
|
msg += f"please pip install '{mitigation}'."
|
|
else:
|
|
msg += f"please pip install '{top_level}'."
|
|
else:
|
|
msg += f"Please pip install '{package}'."
|
|
raise ImportError(msg) from e
|