Skip to content
Tutorials Center
My learning

Topics

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.

Python
async def fetch():
    await asyncio.sleep(0.1)
    return "done"

Try it

Python Coroutines and tasks

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.

Python async for, async with and forgotten awaits

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

Python
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; forgetting await produces the warning "coroutine ... was never awaited" and no result.
  • Await runs sequentially. await a(); await b() runs one after the other. Use gather(), a task group, or create_task() to overlap them.
  • Never block the loop. time.sleep(), heavy computation or blocking I/O freezes every task. Use await asyncio.sleep(), async libraries, or asyncio.to_thread().
  • Cancellation is delivered as asyncio.CancelledError at an await. Do not swallow it; let it propagate after cleanup.
  • Comprehensions can contain await and async for inside 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.TaskGroup and asyncio.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 with asyncio.run(main()).