Predict the output
The handler has a 0.1 s budget and calls a dependency that takes 1 s. What prints?
import asyncio
async def slow_dependency() -> str:
await asyncio.sleep(1)
return "data"
async def handler() -> str:
try:
async with asyncio.timeout(0.1):
return await slow_dependency()
except TimeoutError:
return "fallback"
print(asyncio.run(handler()))Hint 1 of 1
What does asyncio.timeout raise when it expires?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A fallback
Correct. asyncio.timeout cancels the call at 0.1 s and raises TimeoutError, which the handler catches.
asyncio.timeout sets a deadline on the block. When it passes, the inner await is cancelled and the context manager turns that into TimeoutError, which the handler catches to return the fallback.
Why not the others?
- B
data. The dependency needs 1 s; the budget is 0.1 s. - C It raises CancelledError. asyncio.timeout converts the cancellation into TimeoutError.
- D It prints nothing and hangs. The timeout cancels the sleep.