A high-performance, type-safe Mediator pattern implementation for Python 3.13+, built on top of flow-res and injector.
- Result-Driven Development: Built-in support for
flow-resResult types, making error handling explicit and type-safe. - Auto-Registration: Handlers are automatically registered using Python 3.13's
__init_subclass__and generic introspection. - Dependency Injection: Seamless integration with the
injectorlibrary for robust dependency management. - Native Async Support: Designed from the ground up for
asynciowithAwaitableResultsupport for elegant method chaining. - Strict Type Safety: Fully compatible with
pyrightandmypyusing modern Python 3.13 type parameters.
pip install flow-medfrom flow_res import Result
from flow_med import Request
class GetUserRequest(Request[Result[str, Exception]]):
def __init__(self, user_id: int):
self.user_id = user_idHandlers are automatically registered when defined. Use @override to ensure correct implementation.
from typing import override
from flow_res import Ok, Result
from flow_med import RequestHandler
class GetUserHandler(RequestHandler[GetUserRequest, Result[str, Exception]]):
@override
async def handle(self, request: GetUserRequest) -> Result[str, Exception]:
# Logic to get user
return Ok(f"User {request.user_id}")import asyncio
from injector import Injector
from flow_med import Mediator
async def main():
# Initialize with an Injector
Mediator.initialize(Injector())
# Send request and chain results using flow-res
result = await (
Mediator.send_async(GetUserRequest(user_id=1))
.map(lambda name: f"Hello, {name}!")
.unwrap()
)
print(result) # Hello, User 1!
if __name__ == "__main__":
asyncio.run(main())MIT License