How to use asyncio in Python

Python’s asynchronous programming functionality, or async for short, allows you to write programs that get more work done by not waiting for independent tasks to finish. The asyncio library included with Python gives you the tools to use async for processing disk or network I/O without making everything else wait.

asyncio provides two kinds of APIs for dealing with asynchronous operations: high-level and low-level. The high-level APIs are the most generally useful, and they’re applicable to the widest variety of applications. The low-level APIs are powerful, but also complex, and used less frequently.

We’ll concentrate on the high-level APIs in this article. In the sections below, we’ll walk through the most commonly used high-level APIs in asyncio, and show how they can be used for common operations involving asynchronous tasks. 

If you’re completely new to async in Python, or you could use a refresher on how it works, read my introduction to Python async before diving in here.

Run coroutines and tasks in Python

Naturally, the most common use for asyncio is to run the asynchronous parts of your Python script. This means learning to work with coroutines and tasks. 

Python’s async components, including coroutines and tasks, can only be used with other async components, and not with conventional synchronous Python, so you need asyncio to bridge the gap. To do this, you use the function:



Please enter your comment!
Please enter your name here