~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI, Writer of Tidbits, and Linux Enthusiast

Quick Python: Async Callbacks

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

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(message)
                    )
                )
            else:
                callback(message)

Have any questions or want to chat: Reply via Email

Enjoyed this post?

Published a response to this? :