Asynchrony
Asynchrony in Python is a programming model that allows you to run tasks concurrently, without blocking the main flow of the program while waiting for slow operations such as reading files, accessing databases, or making network requests to complete.
Why use asynchrony?
Section titled “Why use asynchrony?”When you run code sequentially (synchronously), if a function takes a long time (for example, to receive data from the internet), the rest of the program stops until it finishes. With asynchrony, you can tell Python:
How is it implemented?
Section titled “How is it implemented?”Python introduces asynchrony using two keywords:
-
asyncio
: you import asyncio to access asynchrony functions -
async
: to define an asynchronous function -
await
: to wait for the result of an asynchronous operation
import asyncio
async def greet():print('Hello')await asyncio.sleep(1) # Wait one secondprint('World')
# Execute the asynchronous functionasyncio.run(greet())
Output:
Hello(wait 1 second)World
Common functions in asyncio
Section titled “Common functions in asyncio”Function | Description |
---|---|
asyncio.run() | Executes a main coroutine from synchronous code. |
asyncio.sleep() | Pauses a coroutine without blocking the main thread. |
asyncio.create_task() | Starts an asynchronous task in the background, without waiting for its result. |
asyncio.wait() | Similar to gather(), but with more control over the wait time and errors. |
asyncio.as_completed() | Executes tasks and allows you to handle the results as they are completed. |
asyncio.TimeoutError | Exception to handle time limits. |
asyncio.gather() | Executes several asynchronous functions at the same time (concurrently) and waits for all of them to finish. |