The get_name() method of the asyncio.Task class in Python

The get_name() method returns the name given to the task either explicitly or through the default parameter.

Task Updated 17 May 2022 1 min read

Overview

  • The method get_name() returns the name of a Task given to it during its creation.
  • The name could have been set through the name parameter of the asyncio.create_task() or through the task.set_name() method.
  • Even if a name is not explicitly given through the name parameter of the asyncio.create_task() method, asyncio provides a default name for the created Task object.

Example

python
# Example Python program that uses the

            # get_name() method to retrieve the name

            # given to an asyncio.Task object

import asyncio

# A simple coroutine in Python

            async def crn():

                await asyncio.sleep(0)

# Print the name of the task

            def print_task_info(task):

                print(task.get_name())

# Create an asyncio task and await for it

            # to complete

            async def main():

                task1 = asyncio.create_task(crn(), name="Simple task")

                task2 = asyncio.create_task(crn())

                task2.set_name("Yet another simple task")

    # Print task names

                print_task_info(task1)

                print_task_info(task2)

                await task1

                await task2

# Execute tasks through asyncio.run()

            eventLoop = asyncio.new_event_loop()

            asyncio.set_event_loop(eventLoop)

            asyncio.run(main())

Output

Output
Simple task

Yet another simple task