The 'remix' your architecture needs: NestJS-style modularity, native async performance, and rigorous typing for Python 3.14+. Less boilerplate, more harmony.
Project description
🎧 dijay
Drop the beat on your dependencies.
dijay is the "remix" your architecture needs: NestJS-style modularity, native async performance, and rigorous typing for Python 3.14+. Less boilerplate, more harmony.
🚀 Features
- Modular Architecture: Organize code into
@modules withimports,providers, andexports. - Constructor Injection: Clean, testable injection via
__init__andAnnotated. - Flexible Scopes:
SINGLETON,TRANSIENT, andREQUEST. - Async Native: First-class support for asynchronous factories and lifecycle hooks.
- Custom Providers:
Providedataclass for value, class and factory bindings. - Lifecycle Hooks:
@on_bootstrapand@on_shutdowndecorators. - Circular Dependency Detection: Immediate
RuntimeErroron cycles.
📦 Installation
uv add dijay
⚡ Quick Start
1. Define Services
from dijay import injectable
@injectable()
class CatsService:
def get_all(self):
return ["Meow", "Purr"]
You can also pass an abstract class as a token to @injectable. This registers the concrete class under the abstract token, enabling dependency inversion:
from abc import ABC, abstractmethod
from dijay import injectable
class Database(ABC):
@abstractmethod
async def query(self, sql: str) -> list: ...
@injectable(Database)
class PostgresDatabase(Database):
async def query(self, sql: str) -> list:
...
Any provider that depends on Database will automatically receive the PostgresDatabase instance.
2. Create a Module
from dijay import module
@module(
providers=[CatsService],
exports=[CatsService],
)
class CatsModule:
pass
3. Bootstrap the App
import asyncio
from dijay import Container, module
@module(imports=[CatsModule])
class AppModule:
pass
async def main():
async with Container.from_module(AppModule) as container:
service = await container.resolve(CatsService)
print(service.get_all())
if __name__ == "__main__":
asyncio.run(main())
Container.from_module(AppModule) scans the module tree, registers all providers, and returns a fully configured Container.
🧩 Modules
Modules are the building blocks of a dijay application. They encapsulate providers and manage dependencies.
@module(
imports=[DatabaseModule],
providers=[UserService],
exports=[UserService],
)
class UserModule: ...
Dynamic Modules
For conditional configuration (e.g. swapping implementations by environment), use a static method that returns a DynamicModule:
import os
from dijay import DynamicModule, module
from .fake import FakeDatabaseModule
from .postgres import PostgresDatabaseModule
@module(
imports=[FakeDatabaseModule],
exports=[FakeDatabaseModule],
)
class DatabaseModule:
@staticmethod
def for_root() -> DynamicModule:
db_module = {
"fake": FakeDatabaseModule,
"postgres": PostgresDatabaseModule,
}[os.getenv("DB_PROVIDER", "fake")]
return DynamicModule(
module=DatabaseModule,
imports=[db_module],
exports=[db_module],
)
💉 Custom Providers
Use Provide to register values, classes or factories directly in a module:
from dijay import module, Provide
@module(providers=[
Provide("DB_URL", use_value="postgresql://localhost/mydb"),
Provide(Cache, use_class=RedisCache),
Provide(HttpClient, use_factory=create_http_client),
])
class InfraModule: ...
| Attribute | Description |
|---|---|
use_value |
Binds a constant value to the token. |
use_class |
Binds a class to instantiate for the token. |
use_factory |
Binds a callable to invoke for the token. |
scope |
Lifetime scope (defaults to SINGLETON). |
💉 Advanced Constructor Injection
Use Annotated with Inject to decouple type hints from injection tokens:
from typing import Annotated
from dijay import Inject, injectable
@injectable()
class Persistence:
def __init__(
self,
conn_string: Annotated[str, Inject("DB_URL")]
):
self.conn = conn_string
🔄 Lifecycle Hooks
dijay supports @on_bootstrap and @on_shutdown decorators to execute logic when the container starts or stops. The most common way to use them is as decorators for methods within @injectable classes:
from dijay import on_bootstrap, on_shutdown, injectable
@injectable()
class Database:
@on_bootstrap
async def connect(self):
print("Database connected!")
@on_shutdown
async def disconnect(self):
print("Database disconnected!")
Hooks can also be defined as standalone functions:
@on_bootstrap
async def log_startup(db: Database):
print("App is starting...")
Hooks can be synchronous or asynchronous and support full dependency injection. They are automatically triggered when using the container as an async context manager:
async with Container.from_module(AppModule):
# @on_bootstrap hooks have already run here
...
# @on_shutdown hooks run when exiting the block
Alternatively, you can call them manually:
container = Container.from_module(AppModule)
await container.bootstrap()
...
await container.shutdown()
🌐 FastAPI Integration
Create a helper to resolve dependencies from the container via FastAPI's Depends:
from typing import Annotated
from fastapi import Depends, Request
def inject[T](token: type[T]) -> T:
"""FastAPI dependency that resolves a token from the container."""
async def use(request: Request) -> T:
return await request.app.state.container.resolve(token, id=str(id(request)))
return Annotated[token, Depends(use)]
Then, use the container as an async context manager and attach it to app.state:
import asyncio
import uvicorn
from fastapi import FastAPI
from dijay import Container, module
@module(...)
class AppModule: ...
app = FastAPI(title="My API", version="0.0.1")
async def main():
async with Container.from_module(AppModule) as container:
app.state.container = container
server = uvicorn.Server(uvicorn.Config(app, host="0.0.0.0", port=8000))
await server.serve()
if __name__ == "__main__":
asyncio.run(main())
For development with reload, use event handlers since uvicorn factories require synchronous return:
def dev():
container = Container.from_module(AppModule)
app.state.container = container
app.add_event_handler("startup", container.bootstrap)
app.add_event_handler("shutdown", container.shutdown)
return app
Use your routes with the inject helper:
@app.get("/")
async def root(service: inject(MyService)):
return await service.do_something()
🔄 Circular Dependency Detection
dijay monitors the resolution stack. If a cycle is detected (e.g., A → B → A), a RuntimeError is raised immediately.
🛠️ Development
uv sync
uv run pytest
uv build
📄 License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dijay-0.3.15.tar.gz.
File metadata
- Download URL: dijay-0.3.15.tar.gz
- Upload date:
- Size: 67.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cf0c1f1ced45053cf83543a881efa192d082fc25380cbb07af46ffa2bbf3d2d4
|
|
| MD5 |
2efb90ba6eab87389900b2b9217f9df8
|
|
| BLAKE2b-256 |
af292835481b2555941ce31883fa425971661d0cb8016b6264828f277820d777
|
File details
Details for the file dijay-0.3.15-py3-none-any.whl.
File metadata
- Download URL: dijay-0.3.15-py3-none-any.whl
- Upload date:
- Size: 11.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
aec7ae610d21cf8aeed2f69203da1f07b605b3c5d657c220f8e872520b186dab
|
|
| MD5 |
b11d261ddf8969f45e256e87e87db4bb
|
|
| BLAKE2b-256 |
696a7075783765a4686b002c872a8784641bb0e8cd1a83493c1093957bb52eb9
|