KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

asyncio.CancelledError

Meldt annulering bij de volgende gelegenheid om de taak na cancel() te hervatten.

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

Syntax

except asyncio.CancelledError:

Meldt annulering bij de volgende gelegenheid om de taak na cancel() te hervatten.

Bewust onderdrukken zet cancelling() niet terug op nul. Om de toestand volledig te verwijderen trekt uncancel() één verzoek van de teller af. Erft van BaseException en valt buiten except Exception. Ruim op in finally en werp de uitzondering na expliciet afvangen gewoonlijk opnieuw op.

In het voorbeeld merkt await de annulering en geeft cancelled() na doorgifte True.

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

Voorbeelden

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

Resultaat

True

In het voorbeeld merkt await de annulering en geeft cancelled() na doorgifte True.

Bronnen