Diy
I really like the Laravel Service Container.
diy is my attempt at recreating something in Python.
After working with FastAPI, I notices some shortcomings in their DI system.
Other solutions in the Python ecosystem also did not satisfy me.
Most of the issues I had are described in the guiding principles section of diys documentation, though no libraries are explicitly mentioned.
Quickstart
There are two important parts in diy.
Specifications contain explicit instructions about how to resolve function parameters, construct types or map protocols/interfaces to a concrete implementation.
import diy
spec = diy.Specification()This is our example class, which only takes one parameter
class ApiClient: def __init__(self, token: str): self.token = token
def get(self, url: str): # imagine an actual implementation here using the tokenThis teaches our container how to build an ApiClient
import os
@spec.builders.decoratedef build_api_client() -> ApiClient: return ApiClient(token=os.environ["API_TOKEN"])The container retrieves a spec, and uses the contained instructions to construct types
container = diy.RuntimeContainer(spec)This is how you get an instance
api_client = diy.resolve(ApiClient)You can also call functions by letting their parameters be resolved from the container
def get_data(api: ApiClient): return api.imaginary_method("")result = diy.call(get_data)Notes
- focus on good error messages
- dependency visualization
- autowiring
- validation