Blog Logo
TAGS

Python Asynchronous Programming Fundamentals

Python introduced asynchronous programming capabilities in version 3.4 in 2014, with further notable improvements in almost every minor version since. This article aims to elucidate the fundamental concepts of asynchronous programming as part of the first step towards mastery. Asynchronous programming provides a way to interleave execution of multiple functions (coroutines) at once; at any given point, only one of the functions is actually doing operations, while the others are waiting for things like blocking I/O to complete (or, if the I/O has already completed, they’re waiting for the current coroutine to be suspended so that they get a chance to resume). Note that, although multiple coroutines can be processed at once, effectively finishing in any order, operations within a single coroutine continue to be executed in the order they’re written. Coroutines can only be called or scheduled by other coroutines. To run a “top-level” coroutine from inside synchronous code (i.e., either inside a non-coroutine function or at module level), the simplest & preferred way is to use the asyncio.run() function introduced in Python 3.7.