Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Cancelling an asyncio task and retrieving its name

Request cancellation, wait for the task to finish, then report its name and whether it was actually cancelled.

Version: Python 3.12

Syntax

task.cancel(msg=None) -> bool
task.cancelled() -> bool
task.get_name() -> str

In Python 3.12, asyncio.Task.cancel requests cancellation. task.cancel() returns True if it makes a request and False if the task is already done. True does not confirm cancellation: unlike asyncio.Future.cancel() on a pending Future, this call does not immediately put the object in the cancelled state. The optional msg parameter was added in Python 3.9; since 3.11, the message is passed on to the code awaiting the cancelled task.

At the next opportunity, the event loop raises asyncio.CancelledError inside the coroutine. Put cleanup in finally. If you catch the exception inside the task, normally re-raise it after cleanup. It inherits from BaseException, so except Exception does not catch it. Suppressing it can let the task keep running and interfere with asyncio.TaskGroup or asyncio.timeout().

After requesting cancellation, use await task to wait for the task to finish. If the task ended by cancellation, the await raises asyncio.CancelledError and task.cancelled() returns True. The request alone is not enough for task.cancelled() to return True.

For the report, use task.get_name() to retrieve the task's name as a str. Set it with asyncio.create_task(..., name=...); without an explicit name, the standard Task implementation generates a default. get_name() has been available since Python 3.8.

Examples

import asyncio


async def worker(started, release):
    try:
        started.set()
        await release.wait()
    finally:
        print("cleanup")


async def main():
    started = asyncio.Event()
    release = asyncio.Event()
    task = asyncio.create_task(worker(started, release), name="worker")
    await started.wait()

    requested = task.cancel()
    print(f"requested={requested}, cancelled={task.cancelled()}")
    try:
        await task
    except asyncio.CancelledError:
        print(f"{task.get_name()}: cancelled={task.cancelled()}")


if __name__ == "__main__":
    asyncio.run(main())

Result

requested=True, cancelled=False
cleanup
worker: cancelled=True

The `started` event ensures the task has entered its `try` block before cancellation is requested. The report prints the name `worker` only after `finally` has run.

Related lessons

  • Python · Lesson 30 · Advanced · Version: 5

Sources