Skip to content

asyncio.print_call_graph() includes its own frame in the call stack #156327

Description

@deadlovelll

Bug report

Bug description:

Currently asyncio-graph.rst shows the example of print_call_graph() usage:

import asyncio

async def test():
    asyncio.print_call_graph()

async def main():
    async with asyncio.TaskGroup() as g:
        g.create_task(test(), name='test')

asyncio.run(main())

with output:

      * Task(name='test', id=0x1039f0fe0)
      + Call stack:
      |   File 't2.py', line 4, in async test()
      + Awaited by:
         * Task(name='Task-1', id=0x103a5e060)
            + Call stack:
            |   File 'taskgroups.py', line 107, in async TaskGroup.__aexit__()
            |   File 't2.py', line 7, in async main()

But actually it mentions print_call_graph() in the graph which is not correct

* Task(name='test', id=0x103d349b0)
  + Call stack:
  |   File '/Users/timofeiivankov/cpython/Lib/asyncio/graph.py', line 276, in print_call_graph()
  |   File '/Users/timofeiivankov/cpython/repro.py', line 4, in async test()
  + Awaited by:
    * Task(name='Task-1', id=0x103d34b90)
      + Call stack:
      |   File '/Users/timofeiivankov/cpython/Lib/asyncio/taskgroups.py', line 125, in async TaskGroup._aexit()
      |   File '/Users/timofeiivankov/cpython/Lib/asyncio/taskgroups.py', line 75, in async TaskGroup.__aexit__()
      |   File '/Users/timofeiivankov/cpython/repro.py', line 7, in async main()

Proposed fix is to increment the depth in print_call_graph():

def print_call_graph(
    future: futures.Future | None = None,
    /,
    *,
    file: io.Writer[str] | None = None,
    depth: int = 1,
    limit: int | None = None,
) -> None:
    """Print the async call graph for the current task or the provided Future."""
    print(format_call_graph(future, depth=depth + 1, limit=limit), file=file)

I have a fix ready for that

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or error

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions