Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

asyncio.shield

Protegge il task dall’annullamento trasmesso tramite l’involucro.

Versione: Python 3.14; repository image, production runtime not attested

Sintassi

await asyncio.shield(aw)

Protegge il task dall’annullamento trasmesso tramite l’involucro.

Il chiamante riceve comunque CancelledError e il task originale continua. Annullare direttamente il task raggiunge anche l’involucro. Conservare un riferimento forte al task.

Nell’esempio outer viene annullato ma il segnale produce True senza annullare 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())

Esempi

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())

Risultato

True True False

Nell’esempio outer viene annullato ma il segnale produce True senza annullare task.

Fonti