Skip to content

Commit 3048493

Browse files
committed
Allow returning a string with format_call_graph
1 parent 0774805 commit 3048493

File tree

2 files changed

+19
-18
lines changed

2 files changed

+19
-18
lines changed

Doc/library/asyncio-graph.rst

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,19 +63,9 @@ and debuggers.
6363
| File 'taskgroups.py', line 107, in async TaskGroup.__aexit__()
6464
| File 't2.py', line 7, in async main()
6565

66-
For rendering the call stack to a string the following pattern
67-
should be used:
68-
69-
.. code-block:: python
70-
71-
import io
72-
73-
...
74-
75-
buf = io.StringIO()
76-
asyncio.print_call_graph(file=buf)
77-
output = buf.getvalue()
66+
.. function:: format_call_graph(*, future=None, depth=1)
7867

68+
Like :func:`print_call_graph`, but returns a string.
7969

8070
.. function:: capture_call_graph(*, future=None)
8171

Lib/asyncio/graph.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
__all__ = (
1313
'capture_call_graph',
14+
'format_call_graph',
1415
'print_call_graph',
1516
'FrameCallGraphEntry',
1617
'FutureCallGraph',
@@ -156,13 +157,15 @@ def capture_call_graph(
156157
return FutureCallGraph(future, call_stack, awaited_by)
157158

158159

159-
def print_call_graph(
160+
def format_call_graph(
160161
*,
161162
future: futures.Future | None = None,
162-
file: typing.TextIO | None = None,
163163
depth: int = 1,
164-
) -> None:
165-
"""Print async call graph for the current task or the provided Future."""
164+
) -> str:
165+
"""Return async call graph as a string for `future`.
166+
167+
If `future` is not provided, format the call graph for the current task.
168+
"""
166169

167170
def render_level(st: FutureCallGraph, buf: list[str], level: int) -> None:
168171
def add_line(line: str) -> None:
@@ -228,9 +231,17 @@ def add_line(line: str) -> None:
228231
try:
229232
buf: list[str] = []
230233
render_level(graph, buf, 0)
231-
rendered = '\n'.join(buf)
232-
print(rendered, file=file)
234+
return '\n'.join(buf)
233235
finally:
234236
# 'graph' has references to frames so we should
235237
# make sure it's GC'ed as soon as we don't need it.
236238
del graph
239+
240+
def print_call_graph(
241+
*,
242+
future: futures.Future | None = None,
243+
file: typing.TextIO | None = None,
244+
depth: int = 1,
245+
) -> None:
246+
"""Print async call graph for the current task or the provided Future."""
247+
print(format_call_graph(future=future, depth=depth), file=file)

0 commit comments

Comments
 (0)