Sub topic 3
Setting Timeouts and Coordinating Asyncio Work
Assume you know Python functions, exceptions, context managers, generators, and the difference between I/O-bound and CPU-bound work. This chapter covers the controls that keep asynchronous programs responsive.
Setting timeouts
Use asyncio.timeout() to limit a block of work. asyncio.wait_for() limits one awaitable. When the limit expires, asyncio cancels the work and raises TimeoutError.
import asyncio
async def fetch():
await asyncio.sleep(2)
return "data"
async def main():
try:
async with asyncio.timeout(1):
print(await fetch())
except TimeoutError:
print("request timed out")
asyncio.run(main())Cancellation gives the coroutine a chance to clean up. Catch CancelledError only when you can clean up, then usually re-raise it.
Limiting and coordinating tasks
A Semaphore limits how many tasks enter a section. A Lock gives one task exclusive access to shared state. An Event lets tasks wait for a signal.
Building pipelines with asyncio.Queue
An asyncio.Queue connects producers and consumers. A bounded queue applies backpressure: put() waits when the queue is full. Call task_done() for every item, then use join() to wait for completion.
Keeping blocking calls off the event loop
Use asyncio.to_thread() for blocking I/O, such as a legacy file or database API. CPU-heavy work usually needs a process pool or another design.
Async iterators, context managers, and generators
An asynchronous generator uses yield inside async def; consume it with async for. An asynchronous context manager uses async with to await setup and cleanup. These forms are useful for streaming data and managing network connections.
Network clients and servers with streams
asyncio.open_connection() returns reader and writer streams for a client. A server created with asyncio.start_server() receives a callback for each connection. Read with await reader.read(), write with writer.write(), and finish with await writer.drain().
Debugging asyncio and avoiding common mistakes
Common errors include forgetting await, creating a coroutine without scheduling it, and calling time.sleep() inside a coroutine. Enable debug mode with asyncio.run(main(), debug=True). Keep task references when you need to inspect or cancel them, and always handle cancellation during cleanup.
Exercise
Which tool should wrap a blocking synchronous call that must run while the event loop remains responsive?
Show answer
Use await asyncio.tothread(blockingfunction, arguments).