It is a basic fact of life that I/O (for example, file or database access) is slow. I/O is not only slow, but also unpredictable. In a common scenario, we wait for data (from a web service or sensors) and write the data to the filesystem or a database. In such a situation, we can find ourselves to be I/O bound—spending more time waiting for the data than actually processing it. We can poll for data periodically or act on event triggers (either check your watch or set an alarm). GUIs usually have special threads that wait for user input in an infinite loop.
The Python asyncio
module for asynchronous I/O uses the concept of coroutines with a related function decorator. A brief example of this module was also given in the Scraping the web recipe of Chapter 5, Web Mining, Databases, and Big Data. Subroutines can be thought of as a special case of coroutines. A subroutine has a start and exit point, either through an early exit with a...