Depends
Dependency
Bases: Generic[T]
Represents a dependency wrapping a callable that returns a value of type T.
Attributes:
Name | Type | Description |
---|---|---|
callable |
Callable[..., T]
|
The callable that provides the dependency. |
__init__(callable)
Initializes the dependency with the provided callable.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
callable
|
Callable[..., T]
|
The callable to wrap as a dependency. |
required |
Provider
Manages dependency overrides for dependency injection.
Attributes:
Name | Type | Description |
---|---|---|
dependency_overrides |
dict
|
A mapping of original dependencies to their overrides. |
__init__()
Initializes an empty dictionary for dependency overrides.
override(dependency, override)
Overrides a given dependency with a new callable.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dependency
|
Callable
|
The original dependency to override. |
required |
override
|
Callable
|
The new callable to use instead of the original. |
required |
Depends(callable)
Creates a Dependency instance wrapping the given callable.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
callable
|
Callable
|
The callable to wrap as a dependency. |
required |
Returns:
Name | Type | Description |
---|---|---|
Dependency |
Dependency
|
An instance of Dependency wrapping the callable. |
Example
provider = Provider()
def get_session() -> Session: ...
@inject(provider) def add_user(user: dict, session: Session = Depends(get_session)): ...
@inject(provider) def mypy_comp_add_user(user: dict, session: Dependency[Session] = Depends(get_session)): ...
inject(provider)
Decorator to inject dependencies into a function based on a provider.
This decorator supports both synchronous and asynchronous functions.
It resolves dependencies using the provided provider
, manages
the context with an exit stack, and calls the original function
with the injected arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
provider
|
Provider
|
An instance responsible for providing dependencies. |
required |
Returns:
Name | Type | Description |
---|---|---|
Callable |
Callable
|
A decorator that wraps the target function, injecting dependencies. |
Examples:
provider = Provider()
def get_session() -> Session:
...
@inject(provider)
def add_user(user: dict, session: Session = Depends(get_session)):
...