Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Deepset ai Haystack LazyImport

From Leeroopedia
Knowledge Sources
Domains Infrastructure, Dependency_Management
Last Updated 2026-02-11 20:00 GMT

Overview

Concrete tool for gracefully handling optional dependency import errors with customizable error messages provided by the Haystack framework.

Description

The LazyImport class is a context manager that extends _DeferredImportExceptionContextManager from the lazy_imports library. When used in a with block, it captures any ImportError that occurs and defers raising it until check() is called. The deferred error includes a user-friendly message suggesting how to install the missing package (e.g., "Try 'pip install transformers'"). Despite its name, it does not delay the actual import; installed modules are imported immediately, and only errors from missing modules are deferred.

This class is the foundation of Haystack's optional dependency system. Components that require optional packages (e.g., transformers, torch, sentence-transformers) use LazyImport to provide graceful degradation and actionable error messages when dependencies are missing.

Usage

Use this class when writing Haystack components or integrations that depend on optional packages. Wrap the import statement in a with LazyImport(): block, then call .check() at the point where the dependency is actually needed (typically in the component's __init__ or warm_up method).

Code Reference

Source Location

Signature

class LazyImport(_DeferredImportExceptionContextManager):
    """
    A context manager that provides controlled handling of import errors.

    It adds the possibility to customize the error messages.

    NOTE: Despite its name, this class does not delay the actual import operation.
    For installed modules: executes the import immediately.
    For uninstalled modules: captures the error and defers it until check() is called.
    """

    def __init__(self, message: str = DEFAULT_IMPORT_ERROR_MSG) -> None:
        """
        Args:
            message: Custom error message template. Use {} as placeholder for package name.
                     Defaults to "Try 'pip install {}'".
        """
        ...

    def __exit__(
        self,
        exc_type: type[Exception] | None,
        exc_value: Exception | None,
        traceback: TracebackType | None,
    ) -> bool | None:
        """
        Exit the context manager. Captures ImportError and defers it.

        Returns:
            True if ImportError was captured (suppresses the exception),
            None otherwise.
        """
        ...

Import

from haystack.lazy_imports import LazyImport

I/O Contract

Inputs

Name Type Required Description
message str No Custom error message template with {} placeholder for package name. Defaults to "Try 'pip install {}'"

Outputs

Name Type Description
context manager LazyImport Context manager that captures ImportError and defers it
check() None or raises Raises the deferred ImportError with custom message if the import failed

Usage Examples

Basic Optional Import

from haystack.lazy_imports import LazyImport

# Wrap optional import in context manager
with LazyImport() as torch_import:
    import torch

# Later, when torch is actually needed:
torch_import.check()  # Raises ImportError with helpful message if torch is not installed

# If torch is installed, use it normally
tensor = torch.zeros(3, 3)

Custom Error Message

from haystack.lazy_imports import LazyImport

with LazyImport(message="Install with: pip install '{}>=4.0'") as transformers_import:
    from transformers import AutoModel

# In a component's __init__ or warm_up:
transformers_import.check()
# If missing: "Haystack failed to import the optional dependency 'transformers'.
#              Install with: pip install 'transformers>=4.0'. Original error: ..."

Usage in a Haystack Component

from haystack import component
from haystack.lazy_imports import LazyImport

with LazyImport() as sentence_transformers_import:
    from sentence_transformers import SentenceTransformer

@component
class MyEmbedder:
    def __init__(self, model: str = "all-MiniLM-L6-v2"):
        sentence_transformers_import.check()  # Fail early with clear message
        self.model_name = model

    def warm_up(self):
        self.model = SentenceTransformer(self.model_name)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment