Prevent cancellation from immediately propagating to a task.
Section: Cancellation and Timeouts
Shield a task from outer cancellation
python
python
import asyncio
async def worker():
await asyncio.sleep(1)
return "finished"
async def main():
task = asyncio.create_task(worker())
try:
await asyncio.wait_for(asyncio.shield(task), timeout=0.1)
except TimeoutError:
print("caller timed out")
print(await task)
asyncio.run(main())Explanation
Use carefully when a task must continue even if the caller times out.
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.
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.