|
1 | 1 | import asyncio
|
| 2 | +import importlib |
2 | 3 | import inspect
|
3 | 4 | import json
|
4 | 5 | import logging
|
| 6 | +import sys |
5 | 7 | import warnings
|
6 | 8 | from contextlib import contextmanager
|
7 | 9 | from enum import Enum
|
8 | 10 | from functools import wraps
|
9 | 11 | from time import time
|
10 |
| -from typing import Any, Callable, Coroutine, Dict, Optional, Sequence |
| 12 | +from typing import Any, Callable, Coroutine, Dict, Optional, Sequence, TypeVar, cast |
11 | 13 | from warnings import warn
|
12 | 14 |
|
13 | 15 | from pydantic import BaseModel
|
14 | 16 | from redis import Redis
|
15 | 17 | from ulid import ULID
|
16 | 18 |
|
| 19 | +T = TypeVar("T") |
| 20 | + |
17 | 21 |
|
18 | 22 | def create_ulid() -> str:
|
19 | 23 | """Generate a unique identifier to group related Redis documents."""
|
@@ -233,3 +237,123 @@ def scan_by_pattern(
|
233 | 237 | from redisvl.redis.utils import convert_bytes
|
234 | 238 |
|
235 | 239 | return convert_bytes(list(redis_client.scan_iter(match=pattern)))
|
| 240 | + |
| 241 | + |
| 242 | +def lazy_import(module_path: str) -> Any: |
| 243 | + """ |
| 244 | + Lazily import a module or object from a module only when it's actually used. |
| 245 | +
|
| 246 | + This function helps reduce startup time and avoid unnecessary dependencies |
| 247 | + by only importing modules when they are actually needed. |
| 248 | +
|
| 249 | + Args: |
| 250 | + module_path (str): The import path, e.g., "numpy" or "numpy.array" |
| 251 | +
|
| 252 | + Returns: |
| 253 | + Any: The imported module or object, or a proxy that will import it when used |
| 254 | +
|
| 255 | + Examples: |
| 256 | + >>> np = lazy_import("numpy") |
| 257 | + >>> # numpy is not imported yet |
| 258 | + >>> array = np.array([1, 2, 3]) # numpy is imported here |
| 259 | +
|
| 260 | + >>> array_func = lazy_import("numpy.array") |
| 261 | + >>> # numpy is not imported yet |
| 262 | + >>> arr = array_func([1, 2, 3]) # numpy is imported here |
| 263 | + """ |
| 264 | + parts = module_path.split(".") |
| 265 | + top_module_name = parts[0] |
| 266 | + |
| 267 | + # Check if the module is already imported and we're not trying to access a specific attribute |
| 268 | + if top_module_name in sys.modules and len(parts) == 1: |
| 269 | + return sys.modules[top_module_name] |
| 270 | + |
| 271 | + # Create a proxy class that will import the module when any attribute is accessed |
| 272 | + class LazyModule: |
| 273 | + def __init__(self, module_path: str): |
| 274 | + self._module_path = module_path |
| 275 | + self._module = None |
| 276 | + self._parts = module_path.split(".") |
| 277 | + |
| 278 | + def _import_module(self): |
| 279 | + """Import the module or attribute on first use""" |
| 280 | + if self._module is not None: |
| 281 | + return self._module |
| 282 | + |
| 283 | + try: |
| 284 | + # Import the base module |
| 285 | + base_module_name = self._parts[0] |
| 286 | + module = importlib.import_module(base_module_name) |
| 287 | + |
| 288 | + # If we're importing just the module, return it |
| 289 | + if len(self._parts) == 1: |
| 290 | + self._module = module |
| 291 | + return module |
| 292 | + |
| 293 | + # Otherwise, try to get the specified attribute or submodule |
| 294 | + obj = module |
| 295 | + for part in self._parts[1:]: |
| 296 | + try: |
| 297 | + obj = getattr(obj, part) |
| 298 | + except AttributeError: |
| 299 | + # Attribute doesn't exist - we'll raise this error when the attribute is accessed |
| 300 | + return None |
| 301 | + |
| 302 | + self._module = obj |
| 303 | + return obj |
| 304 | + except ImportError as e: |
| 305 | + # Store the error to raise it when the module is accessed |
| 306 | + self._import_error = e |
| 307 | + return None |
| 308 | + |
| 309 | + def __getattr__(self, name: str) -> Any: |
| 310 | + # Import the module if it hasn't been imported yet |
| 311 | + if self._module is None: |
| 312 | + module = self._import_module() |
| 313 | + |
| 314 | + # If import failed, raise the appropriate error |
| 315 | + if module is None: |
| 316 | + # Use direct dictionary access to avoid recursion |
| 317 | + if "_import_error" in self.__dict__: |
| 318 | + raise ImportError( |
| 319 | + f"Failed to lazily import {self._module_path}: {self._import_error}" |
| 320 | + ) |
| 321 | + else: |
| 322 | + # This means we couldn't find the attribute in the module path |
| 323 | + raise AttributeError( |
| 324 | + f"{self._parts[0]} has no attribute '{self._parts[1]}'" |
| 325 | + ) |
| 326 | + |
| 327 | + # If we have a module, get the requested attribute |
| 328 | + if hasattr(self._module, name): |
| 329 | + return getattr(self._module, name) |
| 330 | + |
| 331 | + # If the attribute doesn't exist, raise AttributeError |
| 332 | + raise AttributeError(f"{self._module_path} has no attribute '{name}'") |
| 333 | + |
| 334 | + def __call__(self, *args: Any, **kwargs: Any) -> Any: |
| 335 | + # Import the module if it hasn't been imported yet |
| 336 | + if self._module is None: |
| 337 | + module = self._import_module() |
| 338 | + |
| 339 | + # If import failed, raise the appropriate error |
| 340 | + if module is None: |
| 341 | + # Use direct dictionary access to avoid recursion |
| 342 | + if "_import_error" in self.__dict__: |
| 343 | + raise ImportError( |
| 344 | + f"Failed to lazily import {self._module_path}: {self._import_error}" |
| 345 | + ) |
| 346 | + else: |
| 347 | + # This means we couldn't find the attribute in the module path |
| 348 | + raise ImportError( |
| 349 | + f"Failed to find {self._module_path}: module '{self._parts[0]}' has no attribute '{self._parts[1]}'" |
| 350 | + ) |
| 351 | + |
| 352 | + # If the imported object is callable, call it |
| 353 | + if callable(self._module): |
| 354 | + return self._module(*args, **kwargs) |
| 355 | + |
| 356 | + # If it's not callable, this is an error |
| 357 | + raise TypeError(f"{self._module_path} is not callable") |
| 358 | + |
| 359 | + return LazyModule(module_path) |
0 commit comments