The get_stack() method of asyncio.task class

The get_stack() method returns the stack frames of the coroutine that is wrapped by the Task.

Task Updated 13 May 2022 2 min read

Overview

  • The get_stack() method returns the stack frame for the wrapped coroutine of the asyncio.Task, at the place of its suspension.
  • By the time get_stack() is executed, if the Task is already complete or cancelled no stack frame is returned.
  • When the wrapped coroutine of the Task is exited due to an exception, the get_stack() method returns a list of traceback frames.

Example - get_stack() returning a list of traceback frames

python
# Example Python program that prints the stack frames

            # of a coroutine terminated by an exception

            import asyncio

# A coroutine defintion

            async def simplecoro():

                try:

                    for i in range(1, 2):

                        print("Inside simplecoro: %d"%i)

                        raise ValueError("Thrown deliberately")

                        await asyncio.sleep(1)

                except ValueError:

                    raise

# Yet another coroutine defintion

            # that awaits on an object of coroutine simplecoro

            async def samplecoro():

                try:

                    for i in range(1, 10):

                        print("Inside samplecoro: %d"%i)

                        await simplecoro()

                except ValueError:

                    raise

# A coroutine that creates an asyncio.Task

            # and executes it

            async def main():

                try:

                    t1 = asyncio.create_task(samplecoro())

                    await asyncio.sleep(1)

        # Get the stack of the task and print it

                    s1 = t1.get_stack()

                    print(s1)

                    # Suspend main and run t1

                    await t1

                except ValueError as e:

                    print("Handled exception:%s"%e.args)

# Create and event loop and run the task

            el = asyncio.new_event_loop()

            asyncio.set_event_loop(el)

            el.run_until_complete(main())

Output

Output
Inside samplecoro: 1

Inside simplecoro: 1

[<frame at 0x1044718c0, file '/Users/vinodh/pprogs/GetStockEx1.py', line 23, code samplecoro>, <frame at 0x104471540, file '/Users/vinodh/pprogs/GetStockEx1.py', line 13, code simplecoro>]

Handled exception:Thrown deliberately

Example - get_stack() returning the stack frame of a suspended coroutine

python
# Example Python program that prints the

            # stack frame of the wrapped coroutine

            # from an asyncio.Task object

            import asyncio

# Define a coroutine

            async def coro():

                for i in range(1, 10, 2):

                    print(i)

                    # Suspend coro while waiting

                    await asyncio.sleep(1)

# Coroutine that creates and executes Task

            async def main(coro):

                task = asyncio.create_task(coro)

    # Get stack of the wrapped coroutine

                stack = task.get_stack()

                print(stack)

                # Suspend while task is being run

                await task

    # Print the task completion status

                print("Task completed:%s"%task.done())

# Run the coroutine

            el = asyncio.new_event_loop()

            asyncio.set_event_loop(el)

            asyncio.run(main(coro()))

Output

Output
[<frame at 0x10fdfedc0, file '/Users/kpji/getstack_suspend.py', line 7, code coro>]

1

3

5

7

9

Task completed:True