Appendix C. Something Completely Different: Async
Our first two appendixes were for beginning programmers, but this one is for those who are a bit advanced.
Like most programming languages, Python has been synchronous. It runs through code linearly, a line at a time, from top to bottom. When you call a function, Python jumps into its code, and the caller waits until the function returns before resuming what it was doing.
Your CPU can do only one thing at a time, so synchronous execution makes perfect sense. But it turns out that often a program is not actually running any code, but waiting for something, like data from a file or a network service. This is like us staring at a browser screen while waiting for a site to load. If we could avoid this “busy waiting,” we might shorten the total time of our programs. This is also called improving throughput.
In Chapter 15,
you saw that if you want some concurrency,
your choices included threads, processes,
or a third-party solution like gevent
or twisted
.
But there are now a growing number of asynchronous
answers, both built in to Python and third-party solutions.
These coexist with the usual synchronous Python code,
but, to borrow a Ghostbusters warning,
you can’t cross the streams.
I’ll show you how to avoid any ectoplasmic side effects.
Coroutines and Event Loops
In Python 3.4,
Python added a standard asynchronous module
called asyncio
.
Python 3.5 then added the keywords
async
and await
.
These implement some new concepts:
-
Coroutines ...
Get Introducing Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.