Dishka

1.9.1 · active · verified Thu Apr 16

Dishka is a lightweight and performant dependency injection framework for Python, designed to be framework-agnostic and support asynchronous operations and scopes. It leverages type hints for dependency resolution, aiming for a 'cute' and agreeable API. The current version is 1.9.1, and it maintains an active release cadence with frequent minor updates and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define dependencies using `Provider` and `provide`, manage scopes (`Scope.APP`, `Scope.REQUEST`) with `make_container`, and retrieve services. Dependencies are automatically resolved based on type hints.

import asyncio
from dishka import Provider, Scope, provide, make_container

class MyDependency:
    def __init__(self, name: str):
        self.name = name

class MyService:
    def __init__(self, dep: MyDependency):
        self.dep = dep

class MyProvider(Provider):
    @provide(scope=Scope.APP)
    def get_dependency(self) -> MyDependency:
        return MyDependency(name="Global Dep")

    @provide(scope=Scope.REQUEST)
    def get_service(self, dep: MyDependency) -> MyService:
        return MyService(dep)

async def main():
    # 1. Create a container with your providers
    container = make_container(MyProvider())

    # 2. Enter an application scope
    async with container(scope=Scope.APP) as app_container:
        # 3. Enter a request scope (or other child scope)
        async with app_container(scope=Scope.REQUEST) as request_container:
            # 4. Get a dependency from the current scope
            service = await request_container.get(MyService)
            print(f"Service created with dependency name: {service.dep.name}")

    await container.close()

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →