DependantΒΆ
A dependant is any Python function that declares its dependencies by
setting parameter defaults to from_(...). They also can be used as dependencies and
be asynchronous as any other dependency.
Note: By default, each of its dependencies is evaluated only once per injection β subsequent uses are cached.
To override this behavior, use
caching=Falseparameter infrom_(...)orscan(...)functions
Example of dependant that use dependency to get current user:
from fundi import from_
from src.models import User
from src.dependencies import require_user
def application(user: User = from_(require_user)):
print(f"Current user is {user}")
In some cases, you may need to manually specify whether dependency is asynchronous, generator or context manager. To do so β
from_()provides parameters to override default scanning behaviorfrom_(call, *, async_: bool, generator: bool, context: bool)Note that
async_may be used in combination with generator or context to define asynchronous generator or context manager.Also, FunDI will try to define this properties using function return type-hint if defined. To disable this behavior use
use_return_annotation=Falseparameter.
You may want to wrap several dependencies together (e.g., name + ID = username) to pass them as a single unit:
import random
import secrets
from fundi import from_
def require_random_name() -> str:
return random.choice(("Andriy", "Vladyslav", "Yaroslav", "Anatoliy", "Alina"))
def require_unique_id() -> str:
return secrets.token_hex(12)
def require_username(
name: str = from_(require_random_name),
id_: str = from_(require_unique_id)
) -> str:
return f"{name} β {id_}"
def application(username: str = from_(require_username)):
print(f"Using username {username} to hack into your wife's Instagram")
Asynchronous dependants work the same as the synchronous ones.
The key difference is that they are asynchronous (Of course!) and
FunDI will await them when needed.
from fundi import from_
from src.models import User
from src.dependencies import require_user
async def application(user: User = from_(require_user)):
print(f"Current user is {user}")
Dependants can define dependencies inside a positional parameter using the typing.Annotated type-hint.
This may be used to keep logical order of the dependencies inside dependant, or ensure that type-checker would not display false warning:
from typing import Annotated
from fundi import from_
def require_int() -> int:
return 1
def application(value: Annotated[int, from_(require_int)]):
print(f"Resolved {value = }")