diwire¶
Type-driven dependency injection for Python. Zero runtime dependencies.
Fastest DI library in our published benchmarks. See Performance.
diwire is a dependency injection container for Python 3.10+ that builds your object graph from type hints. It supports scopes + deterministic cleanup, async resolution, open generics, and fast steady-state resolution via compiled resolvers.
Installation¶
uv add diwire
Quick start (pure Python)¶
Define your classes. Resolve the top-level one. diwire figures out the rest.
from dataclasses import dataclass, field
from diwire import Container
@dataclass
class Database:
host: str = field(default="localhost", init=False)
@dataclass
class UserRepository:
db: Database
@dataclass
class UserService:
repo: UserRepository
container = Container()
service = container.resolve(UserService)
print(service.repo.db.host) # => localhost
Web frameworks (and task/testing integrations)¶
If you use a framework, start with the integration guides:
For an end-to-end FastAPI example, see Quick start (FastAPI).
What is dependency injection?¶
Dependency injection (DI) is a way to build objects by passing dependencies in, instead of having objects reach out to globals/singletons. It makes dependencies explicit, improves testability, and helps manage resource lifetimes.
If you want a short primer (and when not to use DI), see Dependency injection (DI).
Why diwire¶
Zero runtime dependencies: drop it into any project.
Compiled resolver: build fast resolution paths once with
compile().Scopes + cleanup: per-request caching and deterministic cleanup via generators/async-generators.
Open generics: register
Box[T]once and resolveBox[User]safely.Function injection:
Injected[T]keeps runtime signatures explicit; enable the mypy plugin for precise static signatures.Async support:
aresolve()mirrorsresolve()and async providers are first-class.Framework integration: request-scoped injection patterns for FastAPI, Litestar, aiohttp, Flask, and Django.
Performance¶
For reproducible benchmarks and methodology, see Performance.
What to read next¶
Learning paths - suggested reading order by experience level
Quick start (FastAPI) - end-to-end request-scoped injection in FastAPI
Tutorial (runnable examples) - runnable scripts sourced from
examples/Core concepts - the mental model behind the tutorial (keys, lifetimes, scopes)
How-to guides - frameworks, testing, and patterns
API reference - API reference for the public surface area