Comparing coroutines, by example, in Kotlin and Python

Carmen Alvarez
2 min readJan 2, 2024

--

What’s this about?

I discovered coroutines when working on Android development a few years ago. In more recent times, I’ve been working on backend development, mostly in Python, with a bit of Node.js. When using coroutines in Python, with packages providing async support on top of asyncio, like httpx, SQLAlchemy, or FastAPI, my initial impression was that coroutines were a bit easier to use in these contexts than what I had been used to in Android development. Are coroutines really simpler in Python than in Kotlin? Or have I just not been confronted with complex use cases yet? 🤔

In attempt to reconcile my experiences with the two languages, and in a quest to better understand how they work, I’ve jumped into a few comparative studies, exploring use cases by example.

I’m sharing these examples here, with a few goals:

  • Writing about these examples has forced me to try to better understand the details of coroutines, how to use them, and how some libraries that use them work under the hood (to some extent 😅).
  • Maybe these examples could help somebody else coming from one of the two languages, and learning the other one.

Without further ado, here are the different articles:

📂 Exploring coroutines for file reading, in Kotlin and Python

With a very brief introduction into what a coroutine is, we’ll look at different ways to read a large file without blocking the main thread. We learn how to bridge between threads and coroutines using asyncio in Python and Dispatchers in Kotlin. We also see how to launch multiple tasks in parallel and wait for them all to complete.

🌐 Exploring coroutines for HTTP requests, in Kotlin and Python

We’ll explore making HTTP requests without blocking the main thread. We see different ways to launch multiple tasks in parallel and wait for them all to complete, including using structured concurrency. We see how to cancel ongoing tasks/jobs, and we see similarities between Closeables in Kotlin and context managers in Python.

Sequences and generators in Kotlin and Python

Ok, this isn’t technically about coroutines! But the concept of a suspending function is present with sequences and generators, as it is in coroutines, and it appears that generators laid the foundation for coroutines later on in Python (PEP 342).

🤓 Summary cheat sheets are provided at the end of each of the articles, comparing the APIs between Kotlin and Python.

--

--