pymediate
API Reference

NotificationHandler

API reference for the asynchronous and synchronous NotificationHandler classes.

NotificationHandler defines one subscriber for an Notification type. Several handler classes may subscribe to the same notification.

from abc import ABC, abstractmethod

from pymediate import Notification, NotificationHandler

class NotificationHandler[NotificationT: Notification](ABC):
    @abstractmethod
    async def __call__(self, notification: NotificationT) -> None: ...
Type parameterMeaning
NotificationTThe exact Notification subclass handled by this class

Definition-time validation

When Python defines a notification-handler subclass, PyMediate checks that:

  • NotificationT is an Notification subclass;
  • the subclass defines __call__ with exactly one parameter besides self;
  • that parameter is annotated with the exact NotificationT class;
  • the return annotation is None; and
  • __call__ is async def for pymediate.NotificationHandler and plain def for pymediate.sync.NotificationHandler.

Validation can raise InvalidNotificationTypeError or InvalidHandlerSignatureError. Valid handler classes are recorded in class-definition order. Unlike request handlers, notification handlers do not have a one-handler-per-type restriction.

The asynchronous and synchronous handler classes write to the same process-wide subscription list. Every handler for one exact notification type must use one API; do not mix pymediate.NotificationHandler and pymediate.sync.NotificationHandler for that notification. The asynchronous mediator expects awaitable handlers, while the synchronous mediator calls handlers directly.

Example

from pymediate import NotificationHandler


class RecordOrderMetric(NotificationHandler[OrderPlaced]):
    async def __call__(self, notification: OrderPlaced) -> None:
        print(f"recorded order {notification.order_id}")

Register a RecordOrderMetric instance with the service provider used by the mediator before publishing OrderPlaced.

Introspection method

get_notification_type() returns the declared notification class, or None on an unparameterized base.

See also

On this page