python · level 3 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Set a so one slow reply never hangs your program.
Real services are sometimes slow or broken. waits at most half a second. If the coroutine is not done by then, it is cancelled and you get a , which you can catch like any other error.
With gather, one failing coroutine normally raises its error and you lose every result. Pass return_exceptions=True and each failure comes back as an error object in the results list instead, next to the successes.
import asyncio
async def slow_reply():
await asyncio.sleep(1)
return "finally!"
async def main():
try:
reply = await asyncio.wait_for(slow_reply(), timeout=0.1)
print(reply)
except TimeoutError:
print("Gave up after 0.1 seconds. Try again later.")
asyncio.run(main()) Before Python 3.11 this error was called asyncio.TimeoutError, so you may meet that name in older code.
guess first
One check fails. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import asyncio
async def check(n):
await asyncio.sleep(0.1)
if n == 2:
raise ValueError("bad item")
return n * 10
async def main():
results = await asyncio.gather(check(1), check(2), check(3), return_exceptions=True)
for r in results:
print(type(r).__name__, r)
asyncio.run(main())
your turn
Your turn. Give up on a slow menu server.
The server takes half a second. Pick a shorter time limit in the first blank, and name the error to catch in the second.
fix it
One expired card loses every payment. Fix it!
- One payment fails, and its error wipes out every result. Which
gatheroption keeps the others? - Ask
gatherto hand errors back in the results list instead of raising them. - Add
return_exceptions=Trueinside the brackets ofgather, then run.
nailed it
your async code fails gracefully now. :D
asyncio.wait_forwithtimeout=stops you waiting forever.- Catch
TimeoutErrorand tell the user what happened. return_exceptions=Truekeeps one failure from losing every result.
new words in your collection
- timeout
- TimeoutError
- wait_for
This lesson isn’t saved. A free account remembers every lesson you finish.