CKTIS / Python
asyncio.CancelledError
Segnala l’annullamento alla prossima occasione di riprendere il task dopo cancel().
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
except asyncio.CancelledError:Segnala l’annullamento alla prossima occasione di riprendere il task dopo cancel().
Sopprimere intenzionalmente l’eccezione non azzera cancelling(). Per rimuovere completamente lo stato, uncancel() sottrae una richiesta al contatore. Eredita da BaseException e sfugge a except Exception. Eseguire la pulizia in finally e normalmente rilanciare dopo una cattura esplicita.
Nell’esempio await osserva l’annullamento e cancelled() dà True dopo la propagazione.
import asyncio
async def main():
cleaned = []
async def worker():
try:
await asyncio.Event().wait()
finally:
cleaned.append(True)
t = asyncio.create_task(worker())
await asyncio.sleep(0)
t.cancel()
try:
await t
except asyncio.CancelledError:
assert t.cancelled() and cleaned == [True]
assert not issubclass(asyncio.CancelledError, Exception)
asyncio.run(main())
import asyncio
async def main():
t = asyncio.current_task()
t.cancel()
try:
await asyncio.sleep(0)
except asyncio.CancelledError:
assert t.cancelling() == 1 and t.uncancel() == 0
asyncio.run(main())
Esempi
import asyncio
async def main():
task = asyncio.create_task(asyncio.sleep(60))
await asyncio.sleep(0)
task.cancel()
try:
await task
except asyncio.CancelledError:
print(task.cancelled())
asyncio.run(main())
Risultato
True
Nell’esempio await osserva l’annullamento e cancelled() dà True dopo la propagazione.