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 parameter | Meaning |
|---|---|
NotificationT | The exact Notification subclass handled by this class |
Definition-time validation
When Python defines a notification-handler subclass, PyMediate checks that:
NotificationTis anNotificationsubclass;- the subclass defines
__call__with exactly one parameter besidesself; - that parameter is annotated with the exact
NotificationTclass; - the return annotation is
None; and __call__isasync defforpymediate.NotificationHandlerand plaindefforpymediate.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
- Notification — the published message
- Mediator.publish() — resolves and invokes subscribers
- Notifications — concurrency, ordering, and failure handling
- Errors — validation and dispatch errors