website/content/blog/asynccallbacks.md
2020-07-11 20:47:46 -04:00

854 B

title date draft tags
Quick Python: Async Callbacks 2020-07-11T20:23:29-04:00 false
python

I've written a post on using callbacks in Python. Though to add callbacks to asyncio functions, you'll have to interact with the loop object directly. Replace the emit function in the previous post with the following:

class Application:
    # ...
    def emit(self, message):
        for callback in self.callbacks:
            if asyncio.iscoroutine(callback):
                loop = asyncio.get_running_loop()
                loop.call_soon(
                    functools.partial(
                        asyncio.ensure_future,
                        callback(event, index)
                    )
                )
            else:
                callback(event, index)