Python Reference ยท Statements and Keywords
The async and await keywords
Reference for Python async def and await: define coroutines, run them concurrently with tasks, use async for and async with, and avoid blocking the event loop.
async def defines a coroutine function. Calling it does not run the body; it returns a coroutine object, which must be driven by an event loop. Inside a coroutine, await suspends it until another awaitable (a coroutine, task or future) finishes, letting the event loop run other work in the meantime.
This gives cooperative concurrency in a single thread. It shines for programs that wait a lot, such as network clients and servers, and does not speed up CPU-bound code.
async def fetch(): await asyncio.sleep(0.1) return "done"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
async def name(params): result = await awaitable async for item in async_iterable: ... async with async_context_manager as value: ...
| Construct | Description |
|---|---|
async def |
Defines a coroutine function. If the body also contains yield, it defines an asynchronous generator. |
await expr |
Suspends the coroutine until expr (an awaitable) completes, then evaluates to its result. Valid only inside async def. |
async for |
Iterates over an object with __aiter__() and __anext__(). |
async with |
Uses __aenter__() and __aexit__(). |
Entry points: asyncio.run(coro) starts the loop in a script. asyncio.create_task(coro) schedules a coroutine to run concurrently; asyncio.gather() and asyncio.TaskGroup (3.11+) wait for several.
Raises: TypeError if the awaited object is not awaitable; SyntaxError for await outside an async function (top-level await works in some interactive environments).
Usage notes
- Calling is not running.
work()alone only creates a coroutine; forgettingawaitproduces the warning "coroutine ... was never awaited" and no result. - Await runs sequentially.
await a(); await b()runs one after the other. Usegather(), a task group, orcreate_task()to overlap them. - Never block the loop.
time.sleep(), heavy computation or blocking I/O freezes every task. Useawait asyncio.sleep(), async libraries, orasyncio.to_thread(). - Cancellation is delivered as
asyncio.CancelledErrorat anawait. Do not swallow it; let it propagate after cleanup. - Comprehensions can contain
awaitandasync forinside coroutines. - Not parallelism. Tasks interleave on one thread, so shared state needs far less locking than threads, but one slow step delays all.
- Python 3.11+ added
asyncio.TaskGroupandasyncio.timeout(), which handle errors and deadlines more cleanly than older helpers. - Mixing worlds. A regular function cannot
await; run the loop at the edge of the program and keep the inside async. - Try-it note. In these examples a loop already exists, so they use
await main(); real scripts end withasyncio.run(main()).
Related
asyncio,yield,aiter()andanext(),withconcurrent.futures,threading- Lessons: asyncio, Concurrency