Skip to main content

kerux

CI PyPI Python versions License: MIT

Minimal in-process mediator for Python: requests, notifications and pipeline behaviors. Async first, fully typed.

  • Requests with or without a response, each answered by exactly one handler
  • Notifications published to any number of handlers
  • Pipeline behaviors to wrap requests in logging, validation, timing, transactions, …
  • Async first, with sync handlers welcome and a SyncMediator for programs without asyncio
  • Fully typed: await mediator.send(GetUser(id=1)) is a User to mypy and pyright
  • No dependencies, Python 3.11+, MIT licensed

Kerux (κῆρυξ) is Greek for "herald". It's the Python sibling of Herald for .NET.

Install

pip install kerux
# or
uv add kerux

Getting started

from dataclasses import dataclass

from kerux import Mediator, Notification, Request


@dataclass
class GetUser(Request[User]):  # answered with a User
    id: int


@dataclass
class DeleteUser(Request[None]):  # answered with nothing
    id: int


@dataclass
class UserDeleted(Notification):
    id: int


mediator = Mediator()


@mediator.handler  # the request type comes from the annotation
async def get_user(request: GetUser) -> User:
    return await users.get(request.id)


@mediator.handler
async def delete_user(request: DeleteUser) -> None:
    await users.delete(request.id)
    await mediator.publish(UserDeleted(request.id))


@mediator.notification_handler
async def send_goodbye(notification: UserDeleted) -> None: ...


user = await mediator.send(GetUser(id=1))  # User
await mediator.send(DeleteUser(id=1))  # None

Runnable examples live in examples/: a FastAPI todo API and a CLI.

Requests

A request class declares its response type: Request[User], or Request[None] for no response. Each request type has exactly one handler, which can be:

# a function, async or sync
mediator.register(GetUser, get_user)

# an object with a handle method (or any callable object)
class GetUserHandler:
    def __init__(self, users: UserRepository) -> None:
        self.users = users

    async def handle(self, request: GetUser) -> User:
        return await self.users.get(request.id)

mediator.register(GetUser, GetUserHandler(users))

# a factory, called to create the handler each time the request is sent
mediator.register(GetUser, factory=lambda: GetUserHandler(make_users()))

@mediator.handler registers a function using its first parameter's annotation; @mediator.handler(GetUser) names the type explicitly.

Notifications

A notification can have any number of handlers, registered with register_notification_handler(...) or @mediator.notification_handler. await mediator.publish(notification) runs them one after another, in registration order.

Pipeline behaviors

A behavior wraps every request. Call next() to continue to the next behavior or the handler, or return early to short-circuit:

from kerux import Next


async def logging_behavior(request: object, next: Next) -> Any:
    log.info("Handling %s", type(request).__name__)
    response = await next()
    log.info("Handled %s", type(request).__name__)
    return response


mediator.add_behavior(logging_behavior)  # every request
mediator.add_behavior(validation_behavior, request_type=Validatable)  # only isinstance(request, Validatable)

A behavior added without request_type receives every request, so type checkers require it to accept any request (request: object or Any). Narrow its parameter, e.g. request: Validatable, only together with request_type=Validatable.

Behaviors run in the order added; the first one is the outermost. They also run for Request[None] requests, with None as the response. A behavior can also be an object with a handle(request, next) method.

Sync programs

SyncMediator has the same API without await, for CLI tools and scripts that don't use asyncio:

from kerux import SyncMediator

mediator = SyncMediator()
mediator.register(GetUser, lambda request: users.get(request.id))
user = mediator.send(GetUser(id=1))

Async handlers and behaviors are rejected by SyncMediator: at registration where possible, otherwise when called.

FastAPI

For handlers that need request-scoped dependencies, like a database session, build a Mediator in a FastAPI dependency. It's cheap: a few dictionary inserts.

def get_mediator(db: Annotated[Session, Depends(get_db)]) -> Mediator:
    mediator = Mediator()
    mediator.register(GetUser, factory=lambda: GetUserHandler(db))
    mediator.add_behavior(logging_behavior)
    return mediator


@app.get("/users/{user_id}")
async def read_user(user_id: int, mediator: Annotated[Mediator, Depends(get_mediator)]) -> User:
    return await mediator.send(GetUser(id=user_id))

FastAPI's yield dependencies take care of closing the session. See examples/fastapi_app.py for the full example.

Behaviour

  • Requests and notifications dispatch by exact type: a subclass of a registered request type is not matched.
  • Sending a request without a handler raises HandlerNotFoundError (a LookupError). Registering a second handler for the same request type raises HandlerAlreadyRegisteredError.
  • A handler factory is called only when the pipeline reaches the handler, so a short-circuiting behavior never creates it.
  • Notification handlers run one after another; the first one that raises stops the rest. Publishing without handlers does nothing.
  • In Mediator, sync handlers and behaviors run directly on the event loop. Offload long blocking work yourself, e.g. with asyncio.to_thread.

Coming from Herald or MediatR

Herald / MediatR (.NET) kerux
IRequest<TResponse> / IRequest Request[T] / Request[None]
IRequestHandler<TRequest, TResponse> a function or an object with handle
INotification / INotificationHandler<T> Notification / a function or object
IPipelineBehavior<TRequest, TResponse> async def behavior(request, next)
ISender.Send / IPublisher.Publish await mediator.send(...) / await mediator.publish(...)
Assembly scanning explicit register(...) or decorators

Releasing

Publishing a GitHub release whose tag matches the version in pyproject.toml (e.g. v0.2.0) runs the Publish workflow, which tests, builds and uploads to PyPI via Trusted Publishing.

gh release create v0.2.0 --generate-notes

License

MIT

Metadata

Release files for kerux 0.1.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 kerux 0.1.0
File Size Uploaded Provenance Actions
kerux-0.1.0.tar.gz 13.8 kB With provenance Details for kerux-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kerux 0.1.0
File Interpreter ABI Platform Actions
kerux-0.1.0-py3-none-any.whl Python 3 none any Details for kerux-0.1.0-py3-none-any.whl

Total release size: 25.3 kB

Release files / kerux-0.1.0.tar.gz

Download URL kerux-0.1.0.tar.gz
Size 13.8 kB
Tags Source
SHA-256 checksum
How to use checksums
7284ebd17957a66f13ebb78741b7fd544f3416b2d918775f5bfebe8ec322664d
BLAKE2b-256 checksum
How to use checksums
a1d5f10ac19afae3b4348b5b858d6e078ef9436d3394f6744af3c6d0a2dff1e1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.

Transparency log

Release files / kerux-0.1.0-py3-none-any.whl

Download URL kerux-0.1.0-py3-none-any.whl
Size 11.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f10867dd941ef6efa8a6e9accd0b8582850c07866158d214cd8e92db689ced48
BLAKE2b-256 checksum
How to use checksums
e78d1fecfb9b947498a9842f54c00010e374382b817953a88529caa8917c3407
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.

Transparency log

Security for kerux 0.1.0

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kerux-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.

Transparency log

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.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

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