nuke-di
The simplest dependency injection for async Python projects.
Dependencies are declared with plain type hints. nuke-di builds the dependency tree,
creates every client once and drives its async lifecycle: connect() on startup and
disconnect() on shutdown. Every client starts as soon as its own dependencies have
connected, concurrently with every other client that is ready.
FastAPI, Litestar, FastStream and aiogram handlers, MCP tools and taskiq tasks take clients
by type hint. An optional @entrypoint runs an async function when its module is executed.
It was extracted from the DI layer of a production Python microservice framework and has no runtime dependencies.
- Installation · Quick start · Principles · Performance
- Examples: an executable module · FastAPI
- Documentation
Installation
pip install nuke-di
Requires Python 3.11+.
Quick start
import asyncio
from nuke_di import DI, Client
class Database(Client):
async def connect(self) -> None:
print("database: connected")
async def disconnect(self) -> None:
print("database: disconnected")
async def fetch_user(self, user_id: int) -> str:
return f"user-{user_id}"
class UserService(Client):
def __init__(self, db: Database) -> None:
self._db = db
async def greet(self, user_id: int) -> str:
name = await self._db.fetch_user(user_id)
return f"Hello, {name}!"
async def handler(user_id: int, users: UserService) -> str:
return await users.greet(user_id)
async def main() -> None:
injected = DI.inject(handler) # resolves UserService -> Database
async with DI: # connect() every client, disconnect() on exit
print(await injected(42))
asyncio.run(main())
database: connected
Hello, user-42!
database: disconnected
What happened:
DI.inject(handler)read the type hints ofhandler, found the clientUserService, saw that it needs aDatabasein its__init__and built both.user_id: intis not a client, so it stays a regular argument.async with DIcalledconnect()on every client it built, dependencies first.injected(42)calledhandler(42, users=<UserService>).- Leaving the
async withblock calleddisconnect()in reverse order.
Principles
- A dependency is a class. A subclass of
Clientwith a type-hinted__init__and asyncconnect()/disconnect()is the whole model: no providers, no modules, no registration, no scopes to configure. A third-party object becomes a dependency by wrapping it in such a class. - Type hints are the wiring. A client asks for its dependencies in
__init__, a function in its signature. Nothing else names them, so renaming or adding a dependency is an ordinary refactoring. - Concurrent startup, ordered shutdown. A client connects as soon as its own dependencies have,
concurrently with every other client that is ready, so a slow client holds back only the clients that
need it. They disconnect in reverse, and a failing
disconnect()does not stop the others. - Fail fast. A tree that cannot be built fails before anything connects, naming the argument and
the path to it, and
mypywith the plugin reports the same error before the process starts. A client that cannot connect stops the application once the connected ones are disconnected. There are no retries: restarting is the orchestrator's job. - Tests replace, they do not rewire.
mock()andoverride()put a fake in place of a client for one test; the code under test does not change. - No runtime dependencies. The core uses only the standard library; the framework integrations are extras.
How a startup goes, on the example of the
Clients guide: Consumer needs
only Kafka, so it does not wait for the slow Postgres, and the startup takes as long as its longest chain of
dependencies.
Performance
With real connections the cost of a startup is the waiting, and the structure of the tree decides it. The backend of a product page: an API, four features, and every feature four connections of 100–300 ms, 21 clients:
nuke-di connects every client as soon as its own dependencies have, so the startup takes the longest chain,
0.34 s. dishka and wireup connect one client after another within a get(): 3.41 s, ten times as long, and the
wider the tree, the larger the gap. Gathering the four features by hand brings wireup down
to 0.95 s, and dishka too once its lock is off, which then builds a client that two features share twice.
dependency-injector starts as fast once every client is a Resource written by hand, and stops layer by layer, every layer waiting for its slowest client: 0.66 s against 0.37 s, since Checkout
and EventsProducer, which take 300 ms each to stop, are in different layers. injector has no async lifecycle.
$ uv run python benchmarks/compare.py --only connect --summary
nuke-di 1.14.3 · CPython 3.11.7 · macOS-26.6.2-arm64-arm-64bit · commit 17c8815 · N = 10, 100, 1000 · 20 repeats
nuke-di 1.14.3 · dishka 1.10.1 · wireup 2.12.1 · dependency-injector 4.49.1 · injector 0.24.0
| Lower is better | nuke-di | dishka | wireup | dependency-injector | injector |
|------------------------------------------|------------:|---------------:|---------------:|--------------------:|---------:|
| Startup: 8 clients, connect() of 1–60 ms | **70.8 ms** | 156 ms (2.2×) | 157 ms (2.2×) | **71.5 ms** | — |
| Shutdown: the same 8 clients | **18.8 ms** | 30.9 ms (1.6×) | 30.5 ms (1.6×) | 26.0 ms (1.4×) | — |
| Startup: the product page, 21 clients | **335 ms** | 3.41 s (10.2×) | 3.41 s (10.2×) | **337 ms** | — |
| Shutdown: the product page | **365 ms** | 850 ms (2.3×) | 850 ms (2.3×) | 657 ms (1.8×) | — |
None of the three connects anything when its container is created: unless the application gets the root
at startup, its first request waits for the connections and fails with them. nuke-di connects every client
in async with DI, and a client that cannot connect stops the startup.
benchmarks/compare.py runs the same trees of clients through dishka, wireup, dependency-injector and
injector, each registering the same classes its own way: a cold container with the root resolved, on
classes new to the process, the root again, and one FastAPI request through each library's integration:
$ uv run python benchmarks/compare.py --size 100 --summary
nuke-di 1.11.1 · CPython 3.11.7 · macOS-26.6.2-arm64-arm-64bit · commit 6c2ae10 · N = 100 · 20 repeats
nuke-di 1.11.1 · dishka 1.10.1 · wireup 2.12.1 · dependency-injector 4.49.1 · injector 0.24.0
| Lower is better | nuke-di | dishka | wireup | dependency-injector | injector |
|----------------------------------------------------------|---------------:|----------------:|----------------:|--------------------:|----------------:|
| Cold start: a container and a tree of 100 clients | **541 µs** | 12.9 ms (23.8×) | 20.0 ms (37.0×) | 1.05 ms (1.9×) | 1.34 ms (2.5×) |
| Cold start: the same 100 clients with string annotations | 1.27 ms (1.2×) | 13.7 ms (12.6×) | 21.4 ms (19.6×) | **1.09 ms** | 1.47 ms (1.3×) |
| A cached root | 94.1 ns (2.5×) | 261 ns (7.1×) | 92.6 ns (2.5×) | **37.0 ns** | 1.18 µs (31.9×) |
| A FastAPI request with a client | **103 µs** | 107 µs (1.0×) | 206 µs (2.0×) | 221 µs (2.2×) | — |
So, is nuke-di the fastest? At building a tree with real type hints and at a FastAPI request, yes:
dependency-injector and injector take 2–2.5 times as long for the tree, dishka and wireup 24–37 times as
long, for validating the graph when the container is created, and wireup and dependency-injector twice as
long per request. With string annotations dependency-injector, which reads no annotation, is ahead by a fifth.
On a cached root nuke-di is level with wireup, and the Cython get() of dependency-injector wins by about
50 ns, a difference no application notices.
On its own, resolve() costs 3.5–6.3 µs per client, so a tree of 1000 clients is built in under 5.5 ms,
and connect() adds 13–18 µs per client. docs/benchmarks.md explains every
scenario, records the baseline on Python 3.11–3.14 and has the whole comparison with its method.
An executable module
# report.py
from nuke_di import Client, entrypoint
class Reports(Client):
async def publish(self) -> None:
print("Report published")
@entrypoint
async def main(reports: Reports) -> None:
await reports.publish()
$ python -m report
Report published
The decorator resolves the function's clients, connects them, runs the function and disconnects
the clients on exit. A normal import leaves the function available for a test or another caller.
See Executable modules
for migration and an explicit main() with application-owned arguments.
FastAPI
A path operation takes a client by its type hint, with no Depends and no inject() per handler.
app/clients.py holds the Database and UserService classes of the Quick start, without its
main():
pip install "nuke-di[fastapi]"
# app/api.py
from typing import Annotated
from fastapi import Depends, FastAPI, Header
from app.clients import Database, UserService
from nuke_di.fastapi import setup
app = FastAPI()
setup(app) # before the routes: clients connect on startup, disconnect on shutdown
@app.get("/users/{user_id}")
async def get_user(user_id: int, users: UserService) -> str:
return await users.greet(user_id)
async def current_user(x_user_id: Annotated[int, Header()], db: Database) -> str:
return await db.fetch_user(x_user_id)
@app.get("/me")
async def me(user: Annotated[str, Depends(current_user)]) -> str:
return user
$ uvicorn app.api:app
INFO: Started server process [55625]
INFO: Waiting for application startup.
database: connected
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:51602 - "GET /users/42 HTTP/1.1" 200 OK
INFO: 127.0.0.1:51604 - "GET /me HTTP/1.1" 200 OK
^C
INFO: Shutting down
INFO: Waiting for application shutdown.
database: disconnected
INFO: Application shutdown complete.
INFO: Finished server process [55625]
$ curl localhost:8000/users/42
"Hello, user-42!"
$ curl localhost:8000/me -H "X-User-Id: 7"
"user-7"
The clients connect on startup and disconnect on shutdown, and a dependency such as current_user takes
clients the same way. Importing the app builds nothing, so a test replaces a client before TestClient
starts it:
# tests/test_api.py
from fastapi.testclient import TestClient
from app.api import app
from app.clients import Database
from nuke_di import DI
class FakeDatabase(Database):
async def fetch_user(self, user_id: int) -> str:
return "alice"
def test_get_user() -> None:
with DI.override(Database, FakeDatabase()), TestClient(app) as client:
assert client.get("/users/1").json() == "Hello, alice!"
assert client.get("/me", headers={"X-User-Id": "7"}).json() == "alice"
$ pytest -q tests/test_api.py
. [100%]
1 passed in 0.23s
Routers, websockets and the app's own lifespan are covered in FastAPI; Litestar, FastStream, MCP servers, aiogram and taskiq work the same way.
Documentation
- Clients:
Client, the lifecycle, dataclass clients, connect order, connect and resolution errors - The container:
Dependenciesand the globalDI,resolve(),inject(),mock(),override() - Lifecycle guarantees: ordering, failures, cancellation and their regression tests
- Executable modules:
@entrypoint, explicit process control and migration from 2.x - Frameworks: FastAPI, Litestar, FastStream, MCP servers on the SDK and on FastMCP, aiogram, taskiq, Starlette, Quart and any ASGI app, and servers with an explicit lifespan
- Testing:
mock(),override(), the pytest fixtures, checking the wiring - Configuration: client timeouts and the disconnect deadline
- Errors: every exception and when it is raised
- Examples: runnable scenarios, from a one-off script and a queue worker to FastAPI, Litestar, FastStream, aiogram, taskiq, Starlette, an MCP server and a whole service, each with its output and tests
- Benchmarks: every scenario, the baseline on Python 3.11–3.14 and the comparison with other libraries
- Coding agents: the Agent Skill, a block for
AGENTS.md,llms.txt, Context7 - Development: the checks, coverage and releases
License
Metadata
Release files for nuke-di 3.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| nuke_di-3.0.1.tar.gz | 243.4 kB | With provenance | Details for nuke_di-3.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| nuke_di-3.0.1-py3-none-any.whl | Python 3 | none | any | Details for nuke_di-3.0.1-py3-none-any.whl |
Total release size: 326.8 kB
Release files / nuke_di-3.0.1.tar.gz
| Download URL | nuke_di-3.0.1.tar.gz |
|---|---|
| Size | 243.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5a273ac3cbbf3f33273110706dac8907e9cfb36c0173d02fa40afbad9fd65712
|
|
BLAKE2b-256 checksum How to use checksums |
d6dc8fdd267a8faad74fc0cff9adae40a23f66e441a7d656f38184cf6367dc52
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logRelease files / nuke_di-3.0.1-py3-none-any.whl
| Download URL | nuke_di-3.0.1-py3-none-any.whl |
|---|---|
| Size | 83.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ea38c5dc64dc9e5403b341cd6ec80c4664b5ad60d089bc255ee88cdb3517c6ac
|
|
BLAKE2b-256 checksum How to use checksums |
824bb8c53507c7c3e1e5045384108be402adf14c535268a19dfa4f233596db49
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logSecurity for nuke-di 3.0.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for nuke_di-3.0.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.