Skip to content

Latest commit

 

History

History
92 lines (68 loc) · 8.85 KB

File metadata and controls

92 lines (68 loc) · 8.85 KB

modern-di

GitHub stars Context7 uv Ruff ty

Project Badges
modern-di Supported versions downloads
modern-di-aiogram Supported versions downloads
modern-di-aiohttp Supported versions downloads
modern-di-arq Supported versions downloads
modern-di-celery Supported versions downloads
modern-di-fastapi Supported versions downloads
modern-di-faststream Supported versions downloads
modern-di-flask Supported versions downloads
modern-di-grpc Supported versions downloads
modern-di-litestar Supported versions downloads
modern-di-pytest Supported versions downloads
modern-di-starlette Supported versions downloads
modern-di-taskiq Supported versions downloads
modern-di-typer Supported versions downloads

modern-di is a python dependency injection framework which supports the following:

  • Automatic dependency graph based on type annotations
  • Also, explicit dependencies are allowed where needed
  • Scopes and context management
  • Python 3.10+ support
  • Fully typed and tested
  • Integrations with aiogram, aiohttp, arq, Celery, FastAPI, FastStream, Flask, gRPC, Litestar, Starlette, taskiq, and Typer
  • Pytest integration (modern-di-pytest) — turns any DI dependency into a pytest fixture

Install

uv add modern-di      # or: pip install modern-di

Quick Start

import dataclasses
from modern_di import Container, Group, Scope, providers


@dataclasses.dataclass(kw_only=True, slots=True, frozen=True)
class Settings:
    database_url: str = "postgresql+asyncpg://localhost/app"


@dataclasses.dataclass(kw_only=True, slots=True)
class UserRepository:
    settings: Settings  # auto-injected by type


class Dependencies(Group):
    settings = providers.Factory(Settings, scope=Scope.APP)
    user_repository = providers.Factory(UserRepository, scope=Scope.REQUEST)


with Container(groups=[Dependencies], validate=True) as container:
    with container.build_child_container(scope=Scope.REQUEST) as request:
        repo = request.resolve(UserRepository)
        print(repo.settings.database_url)

See the documentation for scopes, lifecycles, finalizers, and framework integrations. modern-di is deliberately conservative — see Design decisions for what it leaves out on purpose, including auto-binding, in-package integrations, and graph rendering.

Usage examples:

📦 PyPI

📝 License

Part of modern-python

Browse the full list of templates and libraries in modern-python — see the org profile for the categorized index.