Skip to main content

modern-di-taskiq

PyPI version Supported Python versions Downloads Coverage CI License GitHub stars uv Ruff ty

modern-di integration for taskiq.

Full guide: taskiq integration docs

Usage example: examples/

Installation

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

Usage

setup_di stores the container on broker.state and opens it on WORKER_STARTUP. At shutdown it closes the container after every WORKER_SHUTDOWN handler and every middleware shutdown(), so your shutdown code can still resolve Scope.APP dependencies and their finalizers run last. FromDI resolves a provider (or type) into a task parameter through a taskiq dependency, which builds a Scope.REQUEST child container for the task and closes it when the task finishes. No per-task decorator is needed.

import typing

from modern_di import Container, Group, Scope, providers
from modern_di_taskiq import FromDI, setup_di
from taskiq import InMemoryBroker


class Settings:
    def __init__(self) -> None:
        self.greeting = "hello"


class Greeter:
    def __init__(self, settings: Settings) -> None:  # auto-injected by type
        self._settings = settings

    def greet(self, name: str) -> str:
        return f"{self._settings.greeting}, {name}"


class AppGroup(Group):
    settings = providers.Factory(Settings, scope=Scope.APP, cache=True)
    greeter = providers.Factory(Greeter, scope=Scope.REQUEST)


broker = InMemoryBroker()
container = Container(groups=[AppGroup])
setup_di(broker, container)
container.validate()  # optional fail-fast; must come after setup_di registers its providers


@broker.task
async def greet(
    name: str,
    greeter: typing.Annotated[Greeter, FromDI(Greeter)],  # resolve by type
) -> str:
    return greeter.greet(name)

The WORKER_STARTUP/WORKER_SHUTDOWN events fire when the broker's worker process starts and stops, so a script that calls tasks directly (like InMemoryBroker in a test) must drive the container lifecycle itself, for example with async with broker: .... Providers resolve synchronously, but the per-task Scope.REQUEST child is closed with close_async(), so REQUEST-scoped providers can have async finalizers. taskiq.TaskiqMessage is resolvable within DI via the pre-built taskiq_message_provider context provider.

Sharing a container

When one container serves several apps, for example a taskiq worker and a web app in the same process, only one of them should open and close it. Pass manage_lifespan=False and own the root container yourself:

container = Container(groups=[AppGroup])
setup_di(broker, container, manage_lifespan=False)


async def main() -> None:
    async with container:
        await broker.startup()
        ...
        await broker.shutdown()

The worker events then leave the root container alone. Each task still gets its own Scope.REQUEST child, closed when the task ends. APP-scoped finalizers run once, when the async with block exits.

API

Symbol Description
setup_di(broker, container, *, manage_lifespan=True) Stores the root container on broker.state, opens/closes it on worker startup/shutdown, and registers taskiq_message_provider. With manage_lifespan=False it never opens or closes the root container, so the caller owns it; per-task children are built and closed as before. Returns the container
FromDI(dependency, *, use_cache=True) taskiq dependency that resolves a provider instance or a type from the task's Scope.REQUEST child container, building that child on first use; use it as Annotated[T, FromDI(...)] in task signatures. use_cache is passed to TaskiqDepends. Raises RuntimeError naming setup_di when a task reaches it without setup_di called
fetch_di_container(broker) Returns the root container attached to the taskiq broker
taskiq_message_provider ContextProvider for the current taskiq.TaskiqMessage (REQUEST scope)

Part of modern-python

Built on modern-di, a dependency-injection framework with an IoC container and scopes.

Browse the full list of templates and libraries in modern-python; the org profile has the categorized index.

Metadata

Release files for modern-di-taskiq 4.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for modern-di-taskiq 4.2.3
File Size Uploaded Provenance
modern_di_taskiq-4.2.3.tar.gz 5.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for modern-di-taskiq 4.2.3
File Interpreter ABI Platform
modern_di_taskiq-4.2.3-py3-none-any.whl Python 3 none any Details

Total release size: 11.3 kB

Release files / modern_di_taskiq-4.2.3.tar.gz

Download URL modern_di_taskiq-4.2.3.tar.gz
Size 5.6 kB
Tags Source
SHA-256 checksum
How to use checksums
97a205fc9463c51802fc02c269f05c97f3e6e78dc39ae8477201961b7d3dbf6c
BLAKE2b-256 checksum
How to use checksums
b690a61e1d41a9ff548383dbe31ab6a6b2fb0f955908664d2e250df18aff2367
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.4 {"installer":{"name":"uv","version":"0.13.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}

Release files / modern_di_taskiq-4.2.3-py3-none-any.whl

Download URL modern_di_taskiq-4.2.3-py3-none-any.whl
Size 5.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
20cb8327de126cfd88eac15aa6c2e83dbb3fbead0ab4a645d3e419eaaaaf5ab4
BLAKE2b-256 checksum
How to use checksums
11a3581cd59e2ff1df6ad36b472a755a1eb1d152616f57e72652680f743a6255
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.4 {"installer":{"name":"uv","version":"0.13.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}

Security for modern-di-taskiq 4.2.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page