Python Asyncio

asyncio is Python's library for writing concurrent code using async and await. It is especially useful for I/O-bound tasks such as network requests and waiting for external services.

Create an Async Function

Python
Define and run an asynchronous function.
import asyncio

async def greet():
    print("Hello")

asyncio.run(greet())

Using await

The await keyword pauses the current coroutine until another asynchronous operation completes.

Python
Wait asynchronously before continuing.
import asyncio

async def work():
    print("Starting")
    await asyncio.sleep(1)
    print("Finished")

asyncio.run(work())

Create Tasks

Tasks schedule coroutines so they can run concurrently within the event loop.

Python
Run multiple coroutines concurrently.
import asyncio

async def task(name):
    await asyncio.sleep(1)
    print(name)

async def main():
    t1 = asyncio.create_task(task("Task 1"))
    t2 = asyncio.create_task(task("Task 2"))

    await t1
    await t2

asyncio.run(main())

Using asyncio.gather

asyncio.gather() is convenient when you want to wait for multiple awaitable operations together.

Python
Run several asynchronous operations together.
import asyncio

async def work(value):
    await asyncio.sleep(1)
    return value * 2

async def main():
    results = await asyncio.gather(
        work(1),
        work(2),
        work(3)
    )
    print(results)

asyncio.run(main())

Common Use Cases

Asyncio is commonly used for web clients, APIs, network services, asynchronous database operations, and applications handling many I/O operations.

Summary

Python asyncio provides asynchronous programming with async and await. Tasks and gather() make it possible to coordinate multiple I/O-bound operations efficiently.