CKTIS / Python
asyncio.shield
Protège une tâche contre une annulation transmise par l’enveloppe.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
await asyncio.shield(aw)Protège une tâche contre une annulation transmise par l’enveloppe.
L’appelant reçoit toujours CancelledError et la tâche d’origine continue. Une annulation directe de la tâche atteint aussi l’enveloppe. Conserver une référence forte à la tâche.
Dans l’exemple outer est annulée mais le signal donne True sans annuler 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())
Exemples
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())
Résultat
True True False
Dans l’exemple outer est annulée mais le signal donne True sans annuler task.