Last updated:
0 purchases
injected 0.1.1
injected
Simple, type-safe dependency injection in idiomatic Python, inspired by
FastAPI.
Injecting dependencies
from injected import depends, resolver
def get_a() -> int:
return 13
def get_b() -> int:
return 17
@resolver
def get_sum(
a: int = depends(get_a),
b: int = depends(get_b),
) -> int:
return a + b
def test_resolves_dependencies():
assert get_sum() == 30
Seeding the context of a resolver
It's sometimes useful to be able to provide an already resolved value, making it
available throughout the dependency graph. The canonical example of this is how FastAPI
makes things like requests and headers available to all dependencies.
To use this pattern, you specify a sentinel function, get_global_value in the example
below, and then map it to a resolved value in a context passed to seed_context().
from injected import depends, resolver, seed_context
def get_global_value() -> int:
...
@resolver
def calculate_value(a: int = depends(get_global_value)) -> int:
return a + 13
seeded = seed_context(calculate_value, {get_global_value: 31})
def test_can_seed_resolver_context():
assert seeded() == 44
Async dependencies
The @resolver decorator works with both async and non-async functions, with the
restriction that async dependencies can only be used with an async resolver. An async
resolver however, can resolve both async and vanilla dependencies.
import asyncio
from injected import depends, resolver
async def get_a() -> int:
return 13
def get_b() -> int:
return 17
@resolver
async def get_sum(
a: int = depends(get_a),
b: int = depends(get_b),
) -> int:
return a + b
def test_resolves_dependencies():
assert asyncio.run(get_sum()) == 30
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.