APIs and Async · Async Python · lesson 9 of 12
Timeouts and cancellation
about 16 minutes · free · runs in your browser
Deciding when to stop waiting
A request with no timeout can hang forever, and one hung request can hold up everything
behind it. asyncio.wait_for puts a limit on any awaitable:
try:
result = await asyncio.wait_for(slow_thing(), timeout=2.0)
except asyncio.TimeoutError:
result = None
When the timeout fires, the coroutine is cancelled: asyncio.CancelledError is
raised inside it at its current await point. That is worth understanding, because it
means cleanup still runs:
try:
await something()
except asyncio.CancelledError:
await tidy_up()
raise # re-raise; swallowing a cancellation is almost always wrong
Re-raising matters. A coroutine that catches CancelledError and returns normally has
lied to whoever cancelled it.
Your turn: write with_timeout(seconds) that awaits a slow operation and returns
"finished" or "timed out".
You start from this, and edit it in the browser:
import asyncio
async def slow_operation():
await asyncio.sleep(0.2)
return "finished"
async def with_timeout(seconds):
# Return "finished", or "timed out" if it takes too long.
pass