Wrap an awaitable with a timeout.
Section: Cancellation and Timeouts
Use `asyncio.wait_for()`
python
python
import asyncio
async def slow():
await asyncio.sleep(2)
async def main():
try:
await asyncio.wait_for(slow(), timeout=0.5)
except TimeoutError:
print("too slow")
asyncio.run(main())Explanation
A classic timeout helper that cancels the wrapped awaitable if the timeout expires.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Cancellation and Timeouts
Use `asyncio.timeout()`
Apply a deadline with an async context manager.
Shield a task from outer cancellation
Prevent cancellation from immediately propagating to a task.
Add a timeout to queue operations
Wrap queue operations with `wait_for()`.
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.