Patrick Kidger's tinyio Offers a Simple Solution to Event Loops in Python
Designed following dissatisfaction with asyncio, tinyio aims to handle "the simple use cases."
Developer, martial artist, and scuba diver Patrick Kidger has grown tired of fighting with Python's asyncio
library for simple event loops — so has written his own alternative, dubbed tinyio
.
"I wasted a lot of time trying to get correct error propagation with asyncio
, trying to reason whether my tasks would be cleaned up correctly or not (edge-triggered vs level-triggered, etc. etc.)," Kidger explains of the impetus behind the project. "This is an alternative for the simple use cases, where you just need an event loop, and want to crash the whole thing if anything goes wrong. (Raising an exception in every coroutine so it can clean up its resources.)"
The tinyio
library, brought to our attention by Adafruit, is only around 200 lines in length — and, as you might expect, doesn't cover all the use cases of larger and more well-established alternatives like asyncio
or trio
. "You'll definitely still want [asyncio
or trio
] if you need anything fancy," Kidger admits. "If you don't, and you really really want simple error semantics, then maybe tinyio
is for you instead."
Kigder's library is designed to create an event loop, offering a single method which consumes a coroutine and returns its output — using yield
, rather than await
, unusually. "The reason is that await
does not offer a suspension point to an event loop (it just calls __await__
and maybe that offers a suspension point)," the developer explains, "so if we wanted to use that syntax then we'd need to replace yield coro
with something like await tinyio.Task(coro)
. The traditional syntax is not worth the extra class."
Coroutines can yield nothing, a single coroutine, or multiple coroutines, and it's possible to yield a coroutine multiple times. There's also support for threading, allowing functions to run synchronously — and there's support for sleeping, too. Errors, meanwhile, cause all coroutines in the loop to raise tinyio.CancelledError
, along with any threaded functions, and then the original error is raised — an approach which, Kigder explains, "gives every coroutine a chance to shut down gracefully."
The library is available via pip install tinyio
now, with source code on GitHub under the permissive Apache 2 license.