Skip to content

Async Hooks

Applications running on an event loop (FastAPI, Litestar, Starlette, aiohttp) can call the same plugins and hookspecs asynchronously. Implementations may be coroutines, plain functions, or a mix.

import asyncio

from pluxeo import Plugin, PluginManager, hookimpl, hookspec


class Spec:
    @hookspec
    def render_block(self, block): ...


class Remote(Plugin):
    namespace = "acme.renderers"
    name = "remote"

    @hookimpl
    async def render_block(self, block):
        await asyncio.sleep(0)  # stands for an HTTP call
        return f"<remote>{block['text']}</remote>"


class Local(Plugin):
    namespace = "acme.renderers"
    name = "local"

    @hookimpl
    def render_block(self, block):
        return f"<local>{block['text']}</local>"


pm = PluginManager("acme.renderers", hookspec=Spec, discover=False)
pm.register(Remote)
pm.register(Local)
pm.load_all()


async def main():
    return await pm.hook.render_block.aio(block={"text": "hi"})


assert asyncio.run(main()) == ["<remote>hi</remote>", "<local>hi</local>"]

.aio(): in order

await pm.hook.<name>.aio(**kwargs) calls the implementations one after the other, in the same order as the synchronous call, awaiting each coroutine before moving on. It collects non-None results the same way and, for a firstresult hookspec, stops at the first one. Use it by default.

.aio_gather(): concurrently

await pm.hook.<name>.aio_gather(**kwargs) starts every implementation and awaits the coroutines together with asyncio.gather. Use it when the implementations are independent and slow, such as several network calls. It returns the results of the plain functions first, then those of the coroutines, so do not rely on its order. It refuses firstresult hookspecs with TypeError, since "first" has no meaning when everything runs at once.

Rules

  • Calling the synchronous pm.hook.<name>() raises TypeError when any implementation is a coroutine, rather than returning unawaited coroutines. Call .aio() instead.
  • Wrappers are not supported asynchronously. .aio() and .aio_gather() raise NotImplementedError if a hook has a wrapper.
  • Loading stays synchronous. load(), load_all() and unload() are ordinary calls. Run them at startup, before or outside the event loop's request handling.