Skip to main content

The 'remix' your architecture needs: NestJS-style modularity, native async performance, and rigorous typing for Python 3.14+. Less boilerplate, more harmony.

Project description

ci coverage release pypi license

🎧 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 with imports, providers, and exports.
  • Constructor Injection: Clean, testable injection via __init__ and Annotated.
  • Flexible Scopes: SINGLETON, TRANSIENT, and REQUEST.
  • Async Native: First-class support for asynchronous factories and lifecycle hooks.
  • Custom Providers: Provide dataclass for value, class and factory bindings.
  • Lifecycle Hooks: @on_bootstrap and @on_shutdown decorators.
  • Circular Dependency Detection: Immediate RuntimeError on cycles.

📦 Installation

uv add dijay

⚡ Quick Start

1. Define Services

from dijay import injectable

@injectable()
class CatsService:
    def get_all(self):
        return ["Meow", "Purr"]

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

🌐 FastAPI Integration

Integrate dijay using FastAPI's lifespan to manage the container lifecycle:

from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import Depends, FastAPI, Request
from dijay import Container, module

@module(...)
class AppModule: ...

@asynccontextmanager
async def lifespan(app: FastAPI):
    container = Container.from_module(AppModule)
    await container.bootstrap()
    app.state.container = container
    yield
    await container.shutdown()

app = FastAPI(lifespan=lifespan)


def inject[T](token: type[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 Depends(use)


@app.get("/")
async def root(
    service: Annotated[MyService, 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dijay-0.3.2.tar.gz (42.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dijay-0.3.2-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file dijay-0.3.2.tar.gz.

File metadata

  • Download URL: dijay-0.3.2.tar.gz
  • Upload date:
  • Size: 42.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

Hashes for dijay-0.3.2.tar.gz
Algorithm Hash digest
SHA256 d3e76ff5cda38fe92fe92272f1840d72dfa38e9cca8043ef01263e61e5b7b54a
MD5 72c0e88400ffec5ad3c5e460455f57e8
BLAKE2b-256 3ddfdbb7cb540b337c8242462224ed1b700123c4a20f4531f8100c30950df347

See more details on using hashes here.

File details

Details for the file dijay-0.3.2-py3-none-any.whl.

File metadata

  • Download URL: dijay-0.3.2-py3-none-any.whl
  • Upload date:
  • Size: 10.2 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

Hashes for dijay-0.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 8de5f3fe58296d0464271bc63c4d53b442b021d87be06abc5b8c8b60894db04d
MD5 a61cab618c1a98532dc176a3fdabec31
BLAKE2b-256 f342ca818551c10f64c7e7b31501e5eb5424773e5b7e65b882fdbb2905dacdca

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page