Building with an Alternate Model: asyncio

Intuitive Python — by David Muller (28 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Staying Safe When Writing Concurrent Code | TOC | Wrapping Up 👉

A discussion of concurrency in Python is not complete without mentioning the asyncio module. asyncio is noteworthy for several reasons including that it is a recent addition to Python (arriving in Python 3.4) and includes its own special reserved keywords async and await.

So far, we’ve talked about using threads and processes in Python — neither of those had their own dedicated reserved keywords. asyncio is different than threads and processes primarily because asyncio relies on a programming paradigm called cooperative multitasking. The asyncio reserved keywords async and await help facilitate running code in this cooperative multitasking model.

What does cooperative multitasking mean? Let’s learn more about cooperative multitasking in the following figure:

images/asyncio.png

Effectively, a series of jobs are submitted to a single Python process running something called an event loop. The event loop is only ever executing a single job at a time. Each job, however, can explicitly surrender control back to the event loop when, for example, they are waiting for a web request to complete or performing some other long running operation, particularly one…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.