di¶
- class litestar.di.DIContext[source]¶
Bases:
objectA live DI scope. Manages resolution and lifetime of dependencies
- async __aenter__() Self[source]¶
Open this context.
A context can only be entered once. Closing and re-entering it again is an error.
- Raises:
DIContextClosedError – If this context, or its parent context, has already been closed
DIScopeError – If it has already been entered, or its parent has not been
- async __aexit__(exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None) None[source]¶
Close this context and clean up all its dependencies
- __init__(registry: DIRegistry, scope: str | None = None, parent: DIContext | None = None, seeds: Mapping[DependencyKey, Any] | None = None, prepared: PreparedDIContext | None = None) None[source]¶
A DI context to resolve dependencies.
If
scopeis not given, the outermost scope is used, or, whenparentis given, the scope immediately following the parent’s. Creating a context freezesregistry.- Parameters:
registry¶ – The registry to resolve through
scope¶ – The scope this context owns
parent¶ – The context before this
seeds¶ – Values for the seed keys of this scope. If
registrydeclares seeds, values for all seeds must be givenprepared¶ – The
PreparedDIContextofregistry,scopeandparent, which has checked them. If not given, it is created
- enter_nested(registry: DIRegistry | None = None, scope: str | None = None, seeds: Mapping[DependencyKey, Any] | None = None) DIContext[source]¶
A new
DIContext, with this instance set as its parent.async with app_context.enter_nested() as request_context: ...
- get(key: str | TypeForm[Any]) Any[source]¶
Return the previously solved value of
key.- Raises:
DIResolutionError – If the key has not been resolved in this context or a parent
- async inject(fn: Callable[..., Any], args: tuple[Any, ...] = (), kwargs: Mapping[str, Any] | None = None, *, sync_to_thread: bool | None = None) Any[source]¶
Resolve all dependencies of
fn, inject them intofn, and return its return value.argsandkwargsare passed tofn. When a parameter is declared a dependency but still passed explicitly, the explicit form will take precedence.This method should not be used from within a dependency provider, as it can result in deadlocks: When solved dynamically, a dependency can request itself, creating a cycle, which can only be checked exhaustively if all dependencies are declared upfront. A best-effort check is performed to prevent calling this method from within a dependency, but it should not be relied on.
- Parameters:
fn¶ – A callable or an
InjectionTargetargs¶ – Positional arguments for
fnkwargs¶ – Keyword arguments for
fnsync_to_thread¶ – Whether a synchronous
fnruns in a worker thread
- Raises:
MissingProviderError – If a required dependency has no provider.
DIResolutionError – If the call is found to come from inside a factory; a best effort check to avoid misuse.
- async solve(key: str | TypeForm[Any]) Any[source]¶
Solve for
keyand return its value.This method should not be used from within a dependency provider, as it can result in deadlocks: When solved dynamically, a dependency can request itself, creating a cycle, which can only be checked exhaustively if all dependencies are declared upfront. A best-effort check is performed to prevent calling this method from within a dependency, but it should not be relied on.
- Raises:
MissingProviderError – If a key has no provider.
DIResolutionError – If the call is found to come from inside a factory; a best effort check to avoid misuse.
- async solve_arguments(fn: Callable[..., Any], *, supplied: Collection[str] = ()) dict[str, Any][source]¶
Return the resolved dependencies of
fn, keyed by parameter name.Parameters in
suppliedand optional dependencies without a provider are left out.- Parameters:
fn¶ – A callable or an
InjectionTargetsupplied¶ – Names of parameters not to be resolved
- Raises:
MissingProviderError – If a required dependency has no provider.
DIResolutionError – If
suppliednames a parameterfndoes not declare, unlessfntakes**kwargs; or if the call is found to come from inside a factory, a best effort check to avoid misuse.
- async solve_many(*keys: str | TypeForm[Any]) tuple[Any, ...][source]¶
Solve all
keys, and return their resolved values in the order ofkeys.This method should not be used from within a dependency provider, as it can result in deadlocks: When solved dynamically, a dependency can request itself, creating a cycle, which can only be checked exhaustively if all dependencies are declared upfront. A best-effort check is performed to prevent calling this method from within a dependency, but it should not be relied on.
- Raises:
MissingProviderError – If a key has no provider.
DIResolutionError – If the call is found to come from inside a factory; a best effort check to avoid misuse.
- class litestar.di.DIRegistry[source]¶
Bases:
objectA registry of DI providers.
- __init__(name: str, providers: Iterable[Provider], scopes: Iterable[str] | None = None) None[source]¶
A registry of DI providers.
A registry holds every provider needed to satisfy the keys it declares.
A registry is mutable until the first time a graph is solved from it, creating a
DIContextor callingpredecessors_of(), at which point it freezes, validating the graph and disallowing further registrations.- Parameters:
- Raises:
DIRegistrationError – If the scopes or the providers are invalid.
- check_target(target: Callable[..., Any]) None[source]¶
Check that this registry has a provider for every required dependency of
target.- Parameters:
target¶ – A callable or an
InjectionTarget- Raises:
MissingProviderError – If a required dependency of
targethas no provider
- freeze() None[source]¶
Freeze the registry and validate the dependency graph.
Subsequent calls to this method are a no-op.
- Raises:
MissingProviderError – If any dependency has no registered provider
CircularDependencyError – If any provider depends on itself, directly or indirectly
CaptiveDependencyError – If any provider depends on a value from a later scope
- get_provider(key: DependencyKey) Provider | None[source]¶
Return the provider for
key, orNoneif no provider forkeyhas been registered
- predecessors_of(provider: Provider) frozenset[Provider][source]¶
Return predecessors of
provideras declared in this registry.- Raises:
DIRegistrationError – If this registry does not declare
provider.
- property providers: Mapping[DependencyKey, Provider]¶
The registry’s providers
- register(provider: Provider, override: bool = False) None[source]¶
Register a provider.
- Parameters:
provider¶ – The provider or callable to create a provider instance
override¶ – If
False, trying to register a provider for an already existing key raisesDIRegistrationError
- Raises:
DIRegistrationError – If the registry is frozen, the key is a duplicate and
overrideis not set, the scope is unknown, or the provider cannot be inspected.
- register_callable(fn: Callable[..., Any], key: DependencyKey, scope: str | None = None, sync_to_thread: bool | None = None, override: bool = False) None[source]¶
Register a callable as a new provider.
fnwill be wrapped in oneProvider. The key type is inferred fromkey: A string will be a provider for aNamedDependency, anything else aTypeDependency.- Parameters:
fn¶ – The factory callable to create a provider instance from
key¶ – Key to register under
scope¶ – Scope of the new provider
sync_to_thread¶ – Whether a bare sync callable runs in a worker thread: see
Provideroverride¶ – If
False, trying to register a provider for an already existing key raisesDIRegistrationError
- Raises:
DIRegistrationError – If the registry is frozen, the key is a duplicate and
overrideis not set, the scope is unknown, or the provider cannot be inspected.
- class litestar.di.Dependency[source]¶
Bases:
objectMark a parameter as a dependency.
async def handler( session: Annotated[Session, Dependency("db_session")], replica: Annotated[Engine, Dependency(ReplicaEngine)], ) -> None: ...
- key: DependencyKey | None¶
The key to resolve
- kind: Literal['named', 'type'] | ProviderKind | None¶
Whether to resolve by name or by type. If not given, inferred from ‘key’, or by name without a key
- __init__(key: DependencyKey | None = None, kind: Literal['named', 'type'] | ProviderKind | None = None) None¶
- class litestar.di.InjectionParameter[source]¶
Bases:
objectA parameter of a provider or an injection target that DI fills.
- kind: ProviderKind¶
The provider kind
- class litestar.di.InjectionTarget[source]¶
Bases:
objectA callable whose dependencies are read from its signature, for
DIContext.inject(),DIContext.solve_arguments()andDIRegistry.check_target().It has the same calling semantics as a
Provider, but does not provide a value into the context.- __init__(fn: Callable[..., Any], signature: ParsedSignature | None = None) None[source]¶
Wrap
fnas an injection target.- Parameters:
fn¶ – The callable to call with its dependencies resolved
signature¶ – The parsed signature of
fn, used instead of reading it fromfn. For afunctools.partial(), it may be that of the callable it wraps
- property fn: Callable[..., Any]¶
The wrapped callable
- class litestar.di.PreparedDIContext[source]¶
Bases:
objectFactory to create a DIContext, from a given registry, scope, and parent context
- __init__(registry: DIRegistry, scope: str | None = None, parent: DIContext | PreparedDIContext | None = None) None[source]¶
Prepare contexts of
registryatscope, nested inparent.If
scopeis not given, the outermost scope is used, or, whenparentis given, the scope immediately following the parent’s. Freezesregistry.- Parameters:
- Raises:
DIScopeError – If
registryand the registry ofparentdeclare different scopes,registryhas no scopescope, orscopeis not the one following the scope ofparent, without a parent the outermost oneDIContextClosedError – If
parentis a closed contextDIRegistrationError – If
parentis a context andregistrywas created after the outermost context before it was entered
- create(parent: DIContext | None = None, seeds: Mapping[DependencyKey, Any] | None = None) DIContext[source]¶
Return a new
DIContextof the registry at the scope.- Parameters:
parent¶ – The context before the new one: a context of the registry and scope of the
parentgiven to this prepared context, with the outermost context entered after the registry was createdseeds¶ – Values for the seed keys of the scope. If the registry declares seeds, values for all seeds must be given
- class litestar.di.Provide[source]¶
Bases:
objectA dependency declaration, converted at handler registration to a
Providerofdependencyunder the key it is declared with: scope"app"withuse_cache=True,"handler"otherwise, andsync_to_threadas given.
- class litestar.di.Provider[source]¶
Bases:
objectA factory to produce a value
- __init__(fn: Callable[..., Any] | None, kind: Literal['named', 'type'] | ProviderKind | None = None, scope: str = 'handler', key: DependencyKey | None = None, sync_to_thread: bool | None = None, signature: ParsedSignature | None = None) None[source]¶
DI provider. A factory to produce a value.
A factory callable may be:
an async callable
a sync callable: In this case, sync_to_thread must be passed explicitly, to define how it should be invoked. Blocking synchronous callables should pass sync_to_thread=True, so they can run in a thread pool without blocking the main event loop. See Sync vs. Async for more info. A class is treated as a non-blocking sync callable. It’s __init__ and __new__ methods should never block
an async generator, yielding exactly once. The yielded value is the factory value. the code after the
yieldwill be invoked as a cleanup step when this provider’s DIContext closes. If the context is closing with an active exception, that exception will be thrown into the generator. Cleanups are guaranteed to run in reverse order they providers were invoked in. Every cleanup will be invoked, even if prior cleanups raised an exception. Exceptions during cleanup steps are re-raised once all cleanups have completed.a sync generator, yielding exactly once, with the cleanup step of an async generator. The code up to the
yieldruns in a worker thread, the cleanup step in a thread of its own, both in onecontextvars.Context: a context variable set before theyieldis set after it, and set for whoever resolves the provider. A context variable set where the context closes is set for the cleanup step
A provider may declare no ‘fn’, which makes it a seed. Seeds are expected to be given values for their context explicitly when that context is created. The shorthand for this is
Provider.seed()- Parameters:
fn¶ – The factory callable, or
Noneto declare a seed, whose value is given to the context owning its scope when it is builtkind¶ – Whether this provider is keyed by name or by type
scope¶ – Name of the lifetime-scope where the produced value is stored
key¶ – The key to register under. If omitted it is inferred: from
fn.__name__for a named provider, and from the return annotation (or the class itself) for a type providersync_to_thread¶ – Whether a sync callable runs in a worker thread
signature¶ – The parsed signature of
fn, used instead of reading it fromfn. For afunctools.partial(), it may be that of the callable it wraps
- Raises:
DIRegistrationError – If
fnis not a supported callable,keycontradictskind, a seed is declared without a key or with a signature, orsync_to_threadcontradicts the callable’s form.
- property dependencies: tuple[InjectionParameter, ...]¶
Sub-dependencies of this provider
- property non_di_parameters: tuple[str, ...]¶
Names of the factory callable’s parameters that a
functools.partial()binds by keyword
- property request_parameters: tuple[RequestParameter, ...]¶
Sub-dependencies of this provider that carry a parameter or body marker
- class litestar.di.ProviderKind[source]¶
Bases:
StrEnumTypes of provider keys
- __new__(value)¶
- NAMED = 'named'¶
Keyed by a name
- TYPE = 'type'¶
Keyed by a type
- class litestar.di.RequestParameter[source]¶
Bases:
objectParameter of a Provider or InjectionTarget declared by a parameter marker, such as
FromQuery[...], or a body marker, such asJSONBody[...]- field_definition: FieldDefinition¶
The parameter’s declaration. Its
kwarg_definitionis the marker
- marker: ParameterKwarg | BodyKwarg¶
The parameter marker or body marker declaring the parameter
- __init__(parameter_name: str, param_type: ParamType | None, name: str, field_definition: FieldDefinition, marker: ParameterKwarg | BodyKwarg) None¶
- class litestar.di.ValueGraphDivergence[source]¶
Bases:
objectFinding of
check_divergence(): a node at which two registries’ value graphs diverge.provider, declared underkeyby both, has different predecessors inregistrythan infirst_registry
- litestar.di.check_divergence(registries: Iterable[DIRegistry], *, scopes: Collection[str] | None = None, ignore: Iterable[DependencyKey | Provider] | None = None, raise_on_divergence: bool = False) None[source]¶
Check for divergences in the predecessors of providers shared by
registries.Why does this matter? A provider registered in one or more registry that, through differing predecessors in each registry, will create unique values below the lifetimes of its scope.
@provide(scope="app", key="session") async def create_session(engine: NamedDependency[Engine]) -> Session: with Session(bind=engine) as session: yield session @provide(scope="app", key="engine") async def engine_one() -> str: return create_engine(<some params>) @provide(scope="app", key="engine") async def engine_two() -> str: return create_engine(<some other params>) alice = DIRegistry("alice", [create_session, engine_one]) bob = DIRegistry("bob", [create_session, engine_two]) app_ctx = DIContext(registry=DIRegistry(), scope="app") alice_ctx = DIContext(alice, scope="request", parent=app_ctx) bob_ctx = DIContext(alice, scope="request", parent=app_ctx) await alice_ctx.solve("session") # there is now an 'engine' and a 'session' in app_ctx await bob_ctx.solve("session") # a distinct 'engine' and a 'session' are created in app_ctx
In this example, both registries share the provider for the ‘session’ key, but have different providers for the ‘engine’ key. Since ‘session’ depends on ‘engine’, this is a divergence. When resolving ‘session’ through ‘alice_ctx’ , it must get a different ‘engine’ then when resolved through ‘bob_ctx’, which the context will solve by invoking ‘create_session’ again, even if a value for its key is already present in ‘app_ctx’.
- Raises:
DivergenceError – If
raise_on_divergenceis set, at the first finding.
- litestar.di.provide(scope: str = 'handler', kind: Literal['named', 'type'] | ProviderKind | None = None, key: DependencyKey | None = None, sync_to_thread: bool | None = None) Callable[[Callable[..., Any]], Provider][source]¶
A decorator wrapping the callable into a
Provider.- Parameters:
scope¶ – Name of the scope owning the produced value.
kind¶ – Whether the provider is keyed by name or by type. If not given, inferred from
key, or by name without a keykey¶ – Key this factory provides for. If not given, will be inferred. From the callable’s name for
kind="named"(the default), and from the callable’s return type forkind="type"sync_to_thread¶ – Whether a sync callable runs in a worker thread; see
Providerfor more information
- Raises:
DIRegistrationError – If used as a bare
@providewithout parentheses.
- litestar.di.NamedDependency¶
Mark a parameter as a dependency resolved by name.
Equivalent to
Annotated[T, Dependency(kind="named")]
- litestar.di.TypeDependency¶
Mark a parameter as a dependency resolved by type.
Equivalent to
Annotated[T, Dependency(kind="type")]
- litestar.di.DependencyKey = str | type[Any]¶
- exception litestar.di.exceptions.CaptiveDependencyError[source]¶
Bases:
DIGraphErrorA provider depends on a value from a later scope, which it would keep using after that value was cleaned up
- exception litestar.di.exceptions.CircularDependencyError[source]¶
Bases:
DIGraphError
- exception litestar.di.exceptions.DIContextClosedError[source]¶
Bases:
DIResolutionErrorA
DIContextwas used after it was closed.
- exception litestar.di.exceptions.DIException[source]¶
Bases:
LitestarException
- exception litestar.di.exceptions.DIGraphError[source]¶
Bases:
DIException
- exception litestar.di.exceptions.DIRegistrationError[source]¶
Bases:
DIException
- exception litestar.di.exceptions.DIResolutionError[source]¶
Bases:
DIException
- exception litestar.di.exceptions.DIScopeError[source]¶
Bases:
DIResolutionErrorA scope was entered out of order, skipped, repeated, not at all, does not exist
- exception litestar.di.exceptions.DivergenceError[source]¶
Bases:
DIGraphErrorCovering a
ValueGraphDivergence
- exception litestar.di.exceptions.DivergenceWarning[source]¶
Bases:
LitestarWarningCovering a
ValueGraphDivergence
- exception litestar.di.exceptions.MissingProviderError[source]¶
Bases:
DIGraphErrorA dependency has no provider registered in the registry
- exception litestar.di.exceptions.MissingSeedError[source]¶
Bases:
DIResolutionErrorA context was built without a value for a seed key its registry declares at its scope
- exception litestar.di.exceptions.ScopeMismatchError[source]¶
Bases:
DIResolutionErrorA provider exists, but its scope is not entered by the requesting context or any context above it