CKTIS / Python
asyncio.shield
Protege a tarefa do cancelamento transmitido pelo invólucro.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
await asyncio.shield(aw)Protege a tarefa do cancelamento transmitido pelo invólucro.
Quem espera continua a receber CancelledError e a tarefa original prossegue. Cancelar diretamente a tarefa atinge também o invólucro. Guarde uma referência forte à tarefa.
No exemplo outer é cancelado mas o sinal permite obter True sem cancelar task.
import asyncio
async def main():
e = asyncio.Event()
t = asyncio.create_task(e.wait())
s = asyncio.shield(t)
s.cancel()
try:
await s
except asyncio.CancelledError:
assert not t.cancelled()
e.set()
assert await t is True
asyncio.run(main())
Exemplos
import asyncio
async def main():
gate = asyncio.Event()
task = asyncio.create_task(gate.wait())
outer = asyncio.shield(task)
outer.cancel()
gate.set()
print(outer.cancelled(), await task, task.cancelled())
asyncio.run(main())
Resultado
True True False
No exemplo outer é cancelado mas o sinal permite obter True sem cancelar task.