Skip to main content

modern-di-celery

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

modern-di integration for Celery 5.x.

Full guide: Celery integration docs

Usage example: examples/

Installation

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

Usage

setup_di stores the container on app.conf and registers handlers that open and close it on worker_process_init/worker_process_shutdown (once per forked process under the prefork and solo pools) and on worker_init/worker_shutdown (once in the main worker process, the only signals the threads, gevent, and eventlet pools send). @inject builds a Scope.REQUEST child container per task call and resolves the FromDI-marked parameters from it; alternatively set task_cls=DITask to inject every task without a per-task decorator.

import typing

from celery import Celery
from modern_di import Container, Group, Scope, providers
from modern_di_celery import FromDI, inject, setup_di


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)


app = Celery("myapp", broker="redis://localhost")
container = Container(groups=[AppGroup])
setup_di(app, container)
container.validate()  # optional fail-fast check of the provider graph


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

These worker signals fire only when a real celery worker starts and stops, so a script or test that runs tasks eagerly (task_always_eager = True) must drive the container lifecycle itself, either by sending those signals or by opening and closing the container directly. Celery tasks are sync, so REQUEST-scoped finalizers run via close_sync(); there is no framework request/message object, so no context provider is registered.

API

Symbol Description
setup_di(app, container) Stores the root container (Scope.APP) on app.conf and opens/closes it on worker_process_init/worker_process_shutdown and worker_init/worker_shutdown. Returns the container
FromDI(dependency) Inert marker for Annotated[T, FromDI(...)] in task signatures; accepts a provider instance or a type
inject(task) Decorator that builds a Scope.REQUEST child per call, resolves the FromDI-annotated parameters, and closes the child with close_sync() afterwards. Raises TypeError at decoration if the task also declares *args/**kwargs. Raises RuntimeError naming setup_di when a task reaches it without setup_di called
DITask Task subclass that applies @inject to a task's run automatically; pass task_cls=DITask to Celery(...) or base=DITask to @app.task(...)
fetch_di_container(app) Returns the root container (Scope.APP) registered with the Celery app. Raises RuntimeError naming setup_di when called on an app without setup_di called

📦 PyPI

📝 License

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-celery 4.0.0

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-celery 4.0.0
File Size Uploaded
modern_di_celery-4.0.0.tar.gz 5.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for modern-di-celery 4.0.0
File Interpreter ABI Platform
modern_di_celery-4.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 11.1 kB

Release files / modern_di_celery-4.0.0.tar.gz

Download URL modern_di_celery-4.0.0.tar.gz
Size 5.3 kB
Tags Source
SHA-256 checksum
How to use checksums
5ac398ffe4ffb1c2d4f4ebf4e4f42848a524fb96aa4bbc5a95909b8e63da3853
BLAKE2b-256 checksum
How to use checksums
6a14404b3f42df83be02865f52cd8335ae23dc6d2702fde2df6f712a902d7c1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.24 {"installer":{"name":"uv","version":"0.12.24","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_celery-4.0.0-py3-none-any.whl

Download URL modern_di_celery-4.0.0-py3-none-any.whl
Size 5.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bc2671035988b4df8c739aca1b876457b764ba667497d88c0d7832c0f716b456
BLAKE2b-256 checksum
How to use checksums
ecbd283aa5d8e03ee49876eaf67894181c95246009c4dcc52ff28c4ca2511841
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.24 {"installer":{"name":"uv","version":"0.12.24","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 history Release notifications | RSS feed

This release

4.0.0 This release

2 release files

3.1.0

2 release files

3.0.3

2 release files

3.0.2

2 release files

3.0.1

2 release files

3.0.0

2 release files

2.1.0

2 release files

2.0.1

2 release files

2.0.0

2 release files

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