Timeouts and Cancellation
Why timeouts matter
Section titled “Why timeouts matter”Network calls can stall.
Always use timeouts to avoid:
- stuck tasks
- resource leaks
asyncio.wait_for
Section titled “asyncio.wait_for”import asyncio
async def slow():
await asyncio.sleep(5)
return "ok"
async def main():
try:
result = await asyncio.wait_for(slow(), timeout=1)
print(result)
except asyncio.TimeoutError:
print("timed out")
asyncio.run(main())Cancelling a task
Section titled “Cancelling a task”import asyncio
async def worker():
try:
while True:
print("working")
await asyncio.sleep(0.2)
except asyncio.CancelledError:
print("cancelled")
raise
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.7)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("task cancelled confirmed")
asyncio.run(main())Best practices
Section titled “Best practices”- Consider timeouts for all external calls.
- Always handle cancellation cleanly.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – asyncio.wait_for Timeout
Section titled “Exercise 1 – asyncio.wait_for Timeout”Exercise 2 – Cancel a Task
Section titled “Exercise 2 – Cancel a Task”Exercise 3 – Check Cancellation
Section titled “Exercise 3 – Check Cancellation”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading