Dependency injection toolkit
di: dependency injection toolkit
di is a modern dependency injection toolkit, modeled around the simplicity of FastAPI's dependency injection.
- Intuitive: simple API, inspired by FastAPI.
disupports auto-wiring using type annotations.
- Scopes: inspired by pytest scopes, but defined by users (no fixed "request" or "session" scopes).
- Composable: decoupled internal APIs give you the flexibility to customize wiring, execution and binding.
dican execute dependencies in parallel, move sync dependencies to threads and cache results. Performance critical parts are written in 🦀 via graphlib2.
pip install di[anyio]
⚠️ This project is a work in progress. Until there is 1.X.Y release, expect breaking changes. ⚠️
Here is a simple example of how
from dataclasses import dataclass from di import Container, Dependant, SyncExecutor class A: ... class B: ... @dataclass class C: a: A b: B def main(): container = Container() executor = SyncExecutor() solved = container.solve(Dependant(C, scope="request"), scopes=["request"]) with container.enter_scope("request") as state: c = container.execute_sync(solved, executor=executor, state=state) assert isinstance(c, C) assert isinstance(c.a, A) assert isinstance(c.b, B)
For more examples, see our docs.
Why do I need dependency injection in Python? Isn't that a Java thing?
It is a common misconception that traditional software design principles do not apply to Python. As a matter of fact, you are probably using a lot of these techniques already!
For example, the
transport argument to httpx's Client (docs) is an excellent example of dependency injection. Pytest, arguably the most popular Python test framework, uses dependency injection in the form of pytest fixtures.
Most web frameworks employ inversion of control: when you define a view / controller, the web framework calls you! The same thing applies to CLIs (like click) or TUIs (like Textual). This is especially true for many newer web frameworks that not only use inversion of control but also dependency injection. Two great examples of this are FastAPI and BlackSheep.
For a more comprehensive overview of Python projects related to dependency injection, see Awesome Dependency Injection in Python.
This project aims to be a dependency injection toolkit, with a focus on providing the underlying dependency injection functionality for other libraries.
In other words, while you could use this as a standalone dependency injection framework, you may find it to be a bit terse and verbose. There are also much more mature standalone dependency injection frameworks; I would recommend at least looking into python-dependency-injector since it is currently the most popular / widely used of the bunch.
For more background, see our docs.
See this release on GitHub: v0.68.6
Release history Release notifications | RSS feed
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.