Running coroutines in Python with Asyncio

Cassius
Cassandra
Published in
3 min readDec 31, 2020

--

A tutorial on how to use the asyncio library in Python

Photo by Sarah Dorweiler on Unsplash

Asyncio is a programming design that achieves concurrency without multi-threading. It is a single-threaded, single-process design. It uses cooperative multitasking, i.e., it gives a sense of concurrency despite using a single thread in a single process.

Coroutines

At the heart of asyncio are coroutines. Coroutines are declared with the async and await syntax. They are in essence awaitable functions.

To run a coroutine, there are three main mechanisms.

1. Use asyncio.run() This executes the passed coroutine, and once finished, closes the threadpool.

async def printHello():
await asyncio.sleep(1) # do something
print('hello')
asyncio.run(printHello())

2. Use await on an awaitable object. This is an object that is returned by calling a coroutine function.

Below we execute the coroutines printHello and printGoodbye using the await command.

async def printHello():
await asyncio.sleep(1) # do something
print('hello')
async def printGoodbye():
await asyncio.sleep(1) # do something
print('goodbye')

--

--

Cassius
Cassandra

writes about machine learning and programming.