Skip to Content
Introducing Python, 2nd Edition
book

Introducing Python, 2nd Edition

by Bill Lubanovic
November 2019
Beginner
630 pages
12h 20m
English
O'Reilly Media, Inc.
Book available
Content preview from Introducing Python, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Fluent Python, 2nd Edition

Fluent Python, 2nd Edition

Luciano Ramalho

Publisher Resources

ISBN: 9781492051374Errata PageSupplemental Content