lightbulb.di.conditions¶
- class DependencyExpression(order: Sequence[BaseCondition], required: bool)[source]¶
A cached dependency expression. This contains the steps needed to resolve the dependencies for a single function parameter.
- Parameters:
order – The sequence of conditions required to resolve the dependency expression.
required – Whether the dependency expression is required - i.e. can resolve to
None
.
- classmethod create(expr: Any, /) DependencyExpression[Any] [source]¶
Create a dependency expression from a type expression (type hint).
- Parameters:
expr – The type expression to create the dependency expression from.
- Returns:
The created dependency expression.
- async resolve(container: container_.Container, /) T | None [source]¶
Resolve the dependency that satisfies this expression from the given container.
- Parameters:
container – The container to use while satisfying the expression.
- Returns:
The resolved dependency, or
None
if the dependency could not be resolved, andrequired
wasTrue
upon creation.
- class If(inner: type[Any] | UnionType | tuple[Any, ...] | None)[source]¶
Dependency injection condition that will only fall back when the requested dependency is not known to the current container. This is the default when no condition is specified.
Example
@lightbulb.di.with_di async def foo(bar: If[Bar] | None) -> None: # The 'bar' parameter will be 'None' if the 'Bar' dependency # is unregistered. ... # Lightbulb treats the lack of meta annotation as meaning the same as 'If[dep]' @lightbulb.di.with_di async def foo(bar: Bar | None) -> None: # Same as previous example ...
- class Try(inner: type[Any] | UnionType | tuple[Any, ...] | None)[source]¶
Dependency injection condition that will fall back when the requested dependency is either unknown to the current container, or creation raises an exception.
Example
@lightbulb.di.with_di async def foo(bar: Try[Bar] | None) -> None: # The 'bar' parameter will be 'None' if creating the 'Bar' dependency # failed, or is unregistered. ...