The set_name() method of asyncio.Task class in Python

The method set_name() sets the name of an asyncio.task instance. The Python example sets the TaskInfo instances as the names of the task.

Task Updated 17 May 2022 1 min read

Overview

  • The method set_name() sets the name of a Task. The method accepts any Python object as the name, not just a string alone.
  • The value set by the set_name() method is returned by the get_name() method.

Example

python
# Example Python program that uses

            # the Task.set_name() method

            import asyncio

            from datetime import datetime

# Class containing task name and the start

            # time of the task

            class TaskInfo():

                def __init__(self, name, start_time):

                    self.name         = name

                    self.start_time = start_time

    # If an instance of TaskInfo is passed

                # in task.set_name(), the task.get_name()

                # will invoke this __repr__()

                def __repr__(self):

                    return "Task Name: %s; Start time: %s"%(self.name, self.start_time)

# Print the task info

            def printTaskInfo(task):

                print(task.get_name())

# Wrapped coroutine of the task

            async def coro():

                # Suspend while some processing is done

                await asyncio.sleep(0)

# asyncio.run() will execute the coroutine main

            async def main():

                # Create multiple tasks

                for i in range (0, 5):

                    task = asyncio.create_task(coro())

        # Note: Start time is set on task post scheduling it.

                    # If the task is executing for a very small duration,

                    # it is possible that the task would have been finished

                    # now

                    task.set_name(TaskInfo(i, datetime.now()))

        # Print the task information

                    printTaskInfo(task)

        await task

    print("Post await")

# Run tasks through asyncio.run()

            l = asyncio.new_event_loop()

            asyncio.set_event_loop(l)

            asyncio.run(main())

Output

Output
Task Name: 0; Start time: 2022-05-17 13:37:35.193068

Task Name: 1; Start time: 2022-05-17 13:37:35.193282

Task Name: 2; Start time: 2022-05-17 13:37:35.193408

Task Name: 3; Start time: 2022-05-17 13:37:35.193576

Task Name: 4; Start time: 2022-05-17 13:37:35.193717

Post await