On this page
asyncio.shield
Prev: asyncio.set_event_loop_policy | Up: asyncio | Next: asyncio.sleep
Rel: asyncio.AbstractEventLoop, asyncio.AbstractServer, asyncio.all_tasks, asyncio.as_completed
Ref: docs.python.org — asyncio.shield
Tags: #public #python3 #stdlib #asyncio
Import
import asyncio
from asyncio import shield
Signature & Overview
asyncio.shield(arg)
Wait for a future, shielding it from cancellation.
Usage
import asyncio
async def critical() -> str:
await asyncio.sleep(0.01)
return "saved"
async def main():
inner = asyncio.create_task(critical())
shielded = asyncio.shield(inner)
shielded.cancel()
assert await inner == "saved"
asyncio.run(main())
Gotchas
- Keep a reference to the shielded task:
shield()only protects the inner awaitable from cancellation via the outer wrapper; the caller still receivesCancelledError.
REPL Inspect
from asyncio import shield
help(shield)
Linked from
Related notes
- tuts/python3/stdlib_module/asyncio/set_event_loop_policy Linked here; links to this page; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/sleep Linked here; links to this page; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractEventLoop Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractServer Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/all_tasks Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/as_completed Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/Barrier shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/BaseEventLoop shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/BaseProtocol shared tags: #asyncio, #stdlib