async/await is Python syntax for writing coroutines that can pause during long-running operations, allowing an event loop to run other work instead of blocking the application. section 1.1 section 2.1
Use the two keywords for different parts of the coroutine lifecycle:
- Write async def to mark a function as a coroutine. Calling it does not execute its body; it returns a coroutine object. section 2.1.1
- Place await before a coroutine or other awaitable to run it and suspend the containing coroutine until a result is available. section 2.1.2
- Start an entry-point coroutine with asyncio.run, which executes it on the event loop. section 2.1.1
- Create tasks with asyncio.create_task when independent long-running operations should be scheduled concurrently; await them later to collect results and handle completion. section 2.3.1 section 2.3.2
- Prefer asynchronous I/O inside these coroutines. CPU-bound work and blocking I/O can block the single-threaded event loop unless moved to suitable mechanisms. section 2.10 section 2.7.1
Waiting without blocking other coroutines
import asyncio async def add_one(number: int) -> int: return number + 1 async def main() -> None: result = await add_one(1) print(result) asyncio.run(main()) Here, async def creates the coroutine, await pauses main until add_one returns, and asyncio.run drives main to completion. Sequential awaits preserve sequential behavior; tasks are needed to overlap independent long-running operations. section 2.1.2 section 2.1.1
Canceling a task
A task can be canceled with its cancel method. When the task reaches an await point, awaiting it can raise CancelledError, which the surrounding code can handle. Cancellation requests do not instantly stop ordinary Python code. section 2.4.1
Listing 2.4 Using await to wait for the result of coroutine
import asyncio
async def add_one(number: int) -> int:
return number + 1
async def main() -> None:
one_plus_one = await add_one(1) #1
two_plus_one = await add_one(2) #2
print(one_plus_one)
print(two_plus_one)
asyncio.run(main())
Inspect a minimal await example showing how a parent coroutine pauses, receives a result, and continues. section 2.1.2
















