Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Read an asyncio task’s name with `asyncio.Task.get_name()`

`get_name()` returns an asyncio task’s current name as a string. Use it to label a report, and check `cancelled()` separately to tell whether the task was actually cancelled.

Version: Python 3.12

Syntax

task.get_name()  # returns str

task.get_name() is a synchronous instance method on asyncio.Task, available since Python 3.8. It takes no arguments and returns the current name as a str. You do not await it: the name is readable both before and after the task finishes.

Assign a name with asyncio.create_task(coro, name=...), or change it with task.set_name(value), which converts the value to a string. If no name is assigned explicitly, the standard Task implementation generates one when it creates the task. Treat the name as a diagnostic label, not a unique identifier or a status.

task.cancel() requests cancellation but does not guarantee it: the coroutine can catch and suppress asyncio.CancelledError. To report the outcome, use await task to wait for the task to finish, handle the expected asyncio.CancelledError, and check task.cancelled(). The coroutine should normally clean up in finally and let cancellation propagate.

Examples

import asyncio


async def worker(started):
    started.set()
    await asyncio.Event().wait()


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

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


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

Result

report-worker: cancelled=True

The `started` event lets the caller wait for the coroutine to start without a timed delay. The second event is never set, so the task stays pending until cancellation. The report combines the explicit name with the status confirmed after `await task`.

Related lessons

  • Python · Lesson 30 · Advanced · Version: 5

Sources