generating callgraphs in python with mermaid
Generating callsgraphs is very handy, to actually see what your recursion tree is doing. Rather than having to use fancy tools, you can do so with a couple of print statements, like so:
1def func(n):
2 if n > 0:
3 print(f"{n}[func {n}] -->|print| {n}p[{n}]")
4 print(f"{n}[func {n}] -->|call| {n-1}[func {n-1}]")
5 func(n-1)
6
7print('graph TD')
8func(3)
Which outputs the following:
1graph TD
23[func 3] -->|print| 3p[3]
33[func 3] -->|call| 2[func 2]
42[func 2] -->|print| 2p[2]
52[func 2] -->|call| 1[func 1]
61[func 1] -->|print| 1p[1]
71[func 1] -->|call| 0[func 0]
at which point the markdown mermaid extension to render it in the browser:
graph TD
3[func 3] -->|print| 3p[3]
3[func 3] -->|call| 2[func 2]
2[func 2] -->|print| 2p[2]
2[func 2] -->|call| 1[func 1]
1[func 1] -->|print| 1p[1]
1[func 1] -->|call| 0[func 0]
Or you can paste it into the live mermaid editor.