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 resolve Box[User] safely.

  • Function injection: Injected[T] keeps runtime signatures explicit; enable the mypy plugin for precise static signatures.

  • Async support: aresolve() mirrors resolve() 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.