`async` / `await`
async def declares a coroutine function. await pauses it until an awaitable finishes and returns that result. Together they are the syntax of asyncio, not a second thread.
Detailed Explanation
async def fetch(): looks like a function and is a factory for coroutine objects. fetch() does not execute the body. await fetch() does. That split is the first mistake: storing fetch() in a variable without awaiting it creates an object that the garbage collector will warn about.
await accepts awaitables: coroutines, Tasks, Futures, and objects with __await__. It can only appear inside async def (or in an async comprehension). A sync function cannot await. An async function can call a sync function directly; that call runs immediately and, if it blocks, freezes the loop.
async with and async for are the async forms of with and for. They call __aenter__ / __aexit__ and __aiter__ / __anext__. A regular context manager is not legal in async with. Files from open() are sync; use aiofiles or asyncio.to_thread if you need the loop to turn during disk I/O.
Comprehensions: [x async for x in stream] and await inside them need an async function. A list comprehension that calls an async function without await builds a list of coroutines.
Cancellation is task.cancel(), which injects CancelledError at the next await. try / finally still runs. A coroutine that swallows CancelledError cannot be stopped. In 3.8+ CancelledError is a BaseException; do not catch it with except Exception.
async def is also used by other loops (Trio, curio) and by async libraries that are not asyncio. The syntax is shared; the event loop is not. Do not mix asyncio.create_task with a Trio nursery.
Code Examples
import asyncio
async def add(a: int, b: int) -> int:
await asyncio.sleep(0) # yield to the loop
return a + b
async def main() -> None:
print(await add(2, 3)) # 5
pending = add(4, 1) # coroutine, not 5
print(await pending) # 5
# asyncio.run(main())async def read_all(lines) -> list[str]:
return [line async for line in lines]Common Gotchas
Forgetting `await`
the coroutine never runs. Enable warnings; treat "never awaited" as a bug.
`await` in a sync function
`SyntaxError`. Bridge with `asyncio.run` at the top, or `run_coroutine_threadsafe` from a thread.
Catching `Exception` around `await`
you may swallow cancellation on older patterns. Let `CancelledError` propagate, or re-raise it.
`async def` + blocking call is still blocking
the keyword does not make `requests.get` non-blocking.