Repository navigation
Description
Summary
Write a guide for Python users unfamiliar with asynchronous code.
Motivation
Asynchronous programming has become an increasingly important aspect of Python, yet it remains a topic that many Python developers have limited exposure to.
While Python has traditionally been a synchronous language, the introduction of the asyncio library has brought the power of asynchronous I/O to Python, revolutionizing the way we can write and think about our programs.
However, because asyncio was introduced relatively recently (in Python 3.5) and it's optional to use, a significant number of developers are not yet familiar with it. Unlike languages like JavaScript with Node.js, where the asynchronous model is deeply ingrained and unavoidable, Python developers can entirely miss or skip asynchronous programming.
Therefore, a guide on asynchronous programming in Python becomes essential to help developers harness the power of dagger, understand when and how to use it, and to get familiar with its paradigms. This not only opens up new possibilities for developing more efficient applications but also broadens their skill set in the ever-evolving field of programming.
Material
Note
The following sections can be used as source material but also as preliminary documentation for users until the guide is published.
TL;DR: Rules of thumb
Here’s a few rules of thumb that you need to understand first:
- The keyword
asyncbeforedefmeans that the function will become a coroutine. - If a function contains
await, it must be labeled withasync. awaitpauses the execution of the function and gives control back to the event loop. It then waits for its awaitable to complete and returns its result.- An awaitable object is something that you can use in an
awaitexpression. A coroutine is an example of an awaitable object. - You need to kickstart the
Introduction
Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure, or progress.
In Python, asyncio is a library to write single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, running network clients and servers, and other related primitives.
In Python 3.5+, you can use the async/await syntax, which is more straightforward and preferable way to write asynchronous code.
The async Keyword
In Python, async marks a function or method as a coroutine. This function will then be able to use the await keyword, as well as return a coroutine to be awaited by other code.
async def hello_world():
print("Hello, World!")In this case, hello_world is a coroutine function which, when called, returns a coroutine object. It doesn't execute the function immediately.
The await Keyword
The await keyword is used to pause the execution of the coroutine until the result is ready. This allows other tasks to run in the meantime.
async def main():
await hello_world()In this example, main is another coroutine which will call hello_world and wait for its completion before it continues.
Please note:
awaitcan only be used insideasync deffunctions.- If a function contains
await, it must be labeled withasync.
Awaiting on Tasks
To actually run your coroutines, you typically "await" on them within other coroutines.
To kick off this chain of coroutines, you have to start one at the top level. Usually, you'll do this with asyncio.run(), which handles the event loop for you:
import asyncio
asyncio.run(main())asyncio vs AnyIO
asyncio, Python's built-in library for asynchronous programming, provides a solid foundation for writing single-threaded concurrent code. It introduced the async and await keywords, revolutionizing how Python developers could work with asynchronous tasks.
However, at Dagger, we've chosen to leverage AnyIO, a third-party library, for a few key reasons. Firstly, AnyIO provides a more intuitive API that adheres to the principles of structured concurrency. This enforces stricter task lifetimes and makes our asynchronous code easier to reason about, enhancing maintainability and reducing the potential for bugs.
Secondly, AnyIO offers asynchronous file I/O operations, a feature not available in asyncio due to operating system complexities. This allows us to perform non-blocking file operations without reaching for more third-party dependencies, thus preventing potential performance bottlenecks in our I/O-bound tasks.
Finally, AnyIO's compatibility with multiple backends, including AsyncIO itself, provides us with additional flexibility. We're able to switch underlying asynchronous libraries without needing to rewrite our core logic, an advantage that future-proofs our code against the evolving landscape of Python asynchronous libraries.
Concurrency
If you consider these examples where the FastAPI library is tested against multiple Python versions, but in one instance it’s using simple awaits, while the other is using a concurrent task group, there’s a noticeable difference in execution time:
It’s easier to understand why with the following chart:
gantt
title Testing with and without concurrency
dateFormat x
axisFormat %M:%S
section await
Python 3.7 : 68, 37831
Python 3.8 : 37873, 63971
Python 3.9 : 64010, 97783
Python 3.10 : 97824, 128072
Python 3.11 : 128109, 162619
section task group
Python 3.7: 48, 51079
Python 3.8: 58, 50979
Python 3.9: 52, 51978
Python 3.10: 55, 52633
Python 3.11: 56, 59450
See the 📖 Concurrency guide for more.
Running from synchronous code
You can call asynchronous Dagger from any synchronous scope. Just pass the first asynchronous function (coroutine) to anyio.run():
import anyio
import dagger
async def my_dagger_func():
async with dagger.Connection() as client:
...
def my_sync_func():
anyio.run(my_dagger_func)
# do more after that's doneanyio.run kicks off the chain of coroutines in an event loop and waits until it’s all done.
Blocking code
Replace blocking calls (synchronous read/writing from disk, network request, etc) with similar asynchronous versions. For example, dagger already depends on httpx and anyio:
- requests → httpx
- pathlib.Path → anyio.Path
- open → anyio.open_file
Gradual transition
To transition gradually or when you can’t port it to async, use a worker thread:
import time
import anyio
async def main():
await anyio.to_thread.run_sync(time.sleep, 5)
anyio.run(main)In this case, time.sleep(5) is the blocking code, which you can replace with your synchronous I/O calls.
Activity
helderco commentedon May 25, 2023
Updated with more content.