Skip to content

singleton

Decorator that ensures the provider returns the same instance (singleton) for every call within the container's lifecycle.

Parameters:

Name Type Description Default
provider _Provider[T]

The provider function to wrap.

required

Returns:

Type Description
_Provider[T]

_Provider[T]: A provider that always returns the same instance.

Source code in event_sourcery/_event_store/backend.py
def singleton(provider: _Provider[T]) -> _Provider[T]:
    """
    Decorator that ensures the provider returns the same instance (singleton)
    for every call within the container's lifecycle.

    Args:
        provider (_Provider[T]): The provider function to wrap.

    Returns:
        _Provider[T]: A provider that always returns the same instance.
    """
    result: T | None = None

    @wraps(provider)
    def _wrapper(container: "_Container") -> T:
        nonlocal result
        if result is not None:
            return result
        result = provider(container)
        return result

    return _wrapper