Async dependency injection for Python functions
Actively maintained. Last release 11 days ago, commits in 8 of the last 26 weeks. A safe choice.
pip install uncalled-foruncalled-for
Async dependency injection for Python functions.
Declare what your function needs as parameter defaults. They show up resolved when the function runs. No ceremony, no container, no configuration.
from uncalled_for import Depends
async def get_db():
db = await connect()
try:
yield db
finally:
await db.close()
async def handle_request(db: Connection = Depends(get_db)):
await db.execute("SELECT 1")
Features
- Zero dependencies — standard library only
- Async-native — built on
AsyncExitStackandContextVar - Context manager lifecycle — sync and async generators get proper cleanup
- Nested dependencies — dependencies can depend on other dependencies
- Caching — each dependency resolves once per call, even if referenced multiple times
- Call arguments — a factory can reference the arguments of the call it serves
Annotated dependencies
Depends, Shared and CallArgument also work as Annotated metadata, so
you can name a dependency once and reuse it:
DB = Annotated[Connection, Depends(get_db)]
async def handle_request(db: DB):
await db.execute("SELECT 1")
This resolves like db: Connection = Depends(get_db), but to Python db is
still a required parameter. A custom dependency supplies a value from metadata
only if it subclasses Provider; other dependencies there wrap the call.
When something else calls the function with type-checked arguments, such as a
task queue that schedules it, default the parameter to Provided so those
callers can leave it out:
async def handle_request(db: DB = Provided): ...
A type alias works the same way: type DB = Annotated[Connection, Depends(get_db)].
Call arguments
A factory sometimes needs a value from the call itself, not from another
dependency. CallArgument declares that reference:
from uncalled_for import CallArgument, Depends
def load_user(user_id: str = CallArgument()) -> User:
return users[user_id]
async def handle_request(
user_id: str,
user: User = Depends(load_user),
):
...