August 2018
Intermediate to advanced
366 pages
10h 14m
English
In Python, coroutines are implemented through the async def syntax and are executed through an asyncio event loop.
For example, we might write a function that runs two coroutines that count down from a given number of seconds, printing their progress. That would easily allow us to see that the two coroutines are running concurrently, as we would see output from one interleaved with output from the other:
import asyncio
async def countdown(identifier, n):
while n > 0:
print('left:', n, '({})'.format(identifier))
await asyncio.sleep(1)
n -= 1
async def main():
await asyncio.wait([
countdown("A", 2),
countdown("B", 3)
])
Once an event loop is created and we run main within it, we will see the two functions running:
>>> loop ...
Read now
Unlock full access