A general way to show markdowns as a tree according to the calling stack

Usually, markdowns are shown in a linear way even they are generated in different levels of calling stack. For example:


for the code:

from IPython.display import display, Markdown

def factorial(n):
    display(Markdown(f"**n=** {n}"))
    # Base case: if n is 0 or 1, return 1
    if n == 0 or n == 1:
        return 1
    # Recursive case: n * factorial of (n-1)
    else:
        return n * factorial(n - 1)

factorial(5)

What I expect is the markdowns are automatically indented according to the levels of the calling stack. Just as the following:

image

Of course, it is better to make the tree collapsable, just like an interactive tree.

For this specific example, of course, it is easy to adjust the display statement.

I am wondering whether there is a general way so that I don’t need to change the code line by line for the source code of the underlying package may be not available.

Any ideas?

Thanks.