Skip to content

Factory API

sweet_tea.factory.Factory

Bases: BaseFactory

Base factory class for creating instances of registered classes.

This factory provides the core functionality for instantiating classes from the registry with optional filtering by library and label.

Source code in sweet_tea/factory.py
class Factory(BaseFactory):
    """
    Base factory class for creating instances of registered classes.

    This factory provides the core functionality for instantiating classes
    from the registry with optional filtering by library and label.
    """

    _logger = logging.getLogger(__name__)

    @classmethod
    def create(
        cls,
        key: str,
        library: str = "",
        label: str = "",
        configuration: dict[str, Any] | None = None,
    ) -> Any:
        """
        Create an instance of a registered class.

        Args:
            key: Name to reference the class from the registry.
            library: Optional library filter for the class.
            label: Optional label filter for the class.
            configuration: Configuration parameters as keyword arguments.

        Returns:
            Configured instance of the requested class.

        Raises:
            SweetTeaError: When the key is not found or filters don't match.
        """
        # Find all entries that have the specified key value (try multiple variations)
        entries = []
        key_variations = cls._generate_key_variations(key)
        for variation in key_variations:
            entries.extend(
                [entry for entry in cls._registry.entries() if entry.key == variation]
            )
            if entries:  # Found entries with this variation
                break

        return cls._create_from_entries(entries, key, library, label, configuration)

    @classmethod
    def _create_from_entries(
        cls,
        entries: list[Entry],
        key: str,
        library: str,
        label: str,
        configuration: dict[str, Any] | None,
    ) -> Any:
        """
        Create an instance from a filtered list of entries.

        Args:
            entries: List of candidate entries.
            key: The requested key.
            library: Library filter (empty string means no filter).
            label: Label filter (empty string means no filter).
            configuration: Configuration parameters.

        Returns:
            Instantiated and configured class instance.

        Raises:
            SweetTeaError: When no matching entry is found or multiple entries remain after filtering.
        """
        if len(entries) == 0:
            error_message = f"The key {key} not present."
            cls._logger.error(error_message)
            raise SweetTeaError(error_message)

        # If a library filter was specified, filter entries by library
        if library:
            entries = [entry for entry in entries if entry.library == library.lower()]
            if len(entries) == 0:
                error_message = f"The library {library} not present for key {key}."
                cls._logger.error(error_message)
                raise SweetTeaError(error_message)

        # If a label filter was specified, filter entries by label
        if label:
            entries = [entry for entry in entries if entry.label == label.lower()]
            if len(entries) == 0:
                error_message = f"The label {label} not present for key {key}."
                cls._logger.error(error_message)
                raise SweetTeaError(error_message)

        # If more than one entry remains, the filters are insufficient
        if len(entries) > 1:
            error_message = (
                f"The combination of key {key}, label {label}, and library {library} did not return "
                f"a unique result. A total of {len(entries)} possible entries were found."
            )
            cls._logger.error(error_message)
            raise SweetTeaError(error_message)

        # Return instantiated and configured class
        if not configuration:
            configuration = {}
        return entries[0].class_def(**configuration)

create(key, library='', label='', configuration=None) classmethod

Create an instance of a registered class.

Parameters:

Name Type Description Default
key str

Name to reference the class from the registry.

required
library str

Optional library filter for the class.

''
label str

Optional label filter for the class.

''
configuration dict[str, Any] | None

Configuration parameters as keyword arguments.

None

Returns:

Type Description
Any

Configured instance of the requested class.

Raises:

Type Description
SweetTeaError

When the key is not found or filters don't match.

Source code in sweet_tea/factory.py
@classmethod
def create(
    cls,
    key: str,
    library: str = "",
    label: str = "",
    configuration: dict[str, Any] | None = None,
) -> Any:
    """
    Create an instance of a registered class.

    Args:
        key: Name to reference the class from the registry.
        library: Optional library filter for the class.
        label: Optional label filter for the class.
        configuration: Configuration parameters as keyword arguments.

    Returns:
        Configured instance of the requested class.

    Raises:
        SweetTeaError: When the key is not found or filters don't match.
    """
    # Find all entries that have the specified key value (try multiple variations)
    entries = []
    key_variations = cls._generate_key_variations(key)
    for variation in key_variations:
        entries.extend(
            [entry for entry in cls._registry.entries() if entry.key == variation]
        )
        if entries:  # Found entries with this variation
            break

    return cls._create_from_entries(entries, key, library, label, configuration)

Methods

create()

sweet_tea.factory.Factory.create(key, library='', label='', configuration=None) classmethod

Create an instance of a registered class.

Parameters:

Name Type Description Default
key str

Name to reference the class from the registry.

required
library str

Optional library filter for the class.

''
label str

Optional label filter for the class.

''
configuration dict[str, Any] | None

Configuration parameters as keyword arguments.

None

Returns:

Type Description
Any

Configured instance of the requested class.

Raises:

Type Description
SweetTeaError

When the key is not found or filters don't match.

Source code in sweet_tea/factory.py
@classmethod
def create(
    cls,
    key: str,
    library: str = "",
    label: str = "",
    configuration: dict[str, Any] | None = None,
) -> Any:
    """
    Create an instance of a registered class.

    Args:
        key: Name to reference the class from the registry.
        library: Optional library filter for the class.
        label: Optional label filter for the class.
        configuration: Configuration parameters as keyword arguments.

    Returns:
        Configured instance of the requested class.

    Raises:
        SweetTeaError: When the key is not found or filters don't match.
    """
    # Find all entries that have the specified key value (try multiple variations)
    entries = []
    key_variations = cls._generate_key_variations(key)
    for variation in key_variations:
        entries.extend(
            [entry for entry in cls._registry.entries() if entry.key == variation]
        )
        if entries:  # Found entries with this variation
            break

    return cls._create_from_entries(entries, key, library, label, configuration)