Python 3.4+Async programmingfunction
asyncio.shield()
tasks
Protects an awaitable from cancellation: if the waiter is cancelled, the inner task keeps running to completion.
Syntax
result = await asyncio.shield(aw)
Cancellation still reaches the caller: await shield(...) raises CancelledError (or TimeoutError under wait_for), only the inner task does not receive it. Pass a coroutine and shield creates a task you hold no reference to; the loop keeps tasks only by weak references, so it may be garbage-collected. Create the task yourself, keep it, and await it later.
Examples
# Python 3.11+
import asyncio
async def save():
await asyncio.sleep(0.03)
print('сохранено')
async def main():
task = asyncio.create_task(save())
try:
await asyncio.wait_for(asyncio.shield(task), timeout=0.01)
except TimeoutError:
print('тайм-аут, но запись идёт')
await task # держим ссылку и дожидаемся
asyncio.run(main()) # → тайм-аут, но запись идёт / сохранено
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy