How to print the recursive stack in Python
<p>How do I print or show the recursive stack in Python when I'm running a recursive function?</p>

<p>It's not clear what you want but as far as I get your question, you can print the stack of function callers in a recursive manner like the following, using the python <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect module</a>.</p>

<pre><code>import inspect, sys

max_recursion_depth = 10

def rec_func(recursion_index):
    if recursion_index == 0:
        return

    rec_func(recursion_index-1)

    current_frame = inspect.currentframe()
    calframe = inspect.getouterframes(current_frame, 2)

    frame_object = calframe[0][0]

    print("Recursion-%d: %s" % (max_recursion_depth - recursion_index, frame_object.f_locals))
    print("Passed parameters: %s" % (sys._getframe(1).f_locals) )


rec_func(max_recursion_depth)
</code></pre>

<p>You can also use <code>sys.get_frame()</code> to access the current frame and by using the <code>f_locals</code> property, you can access the parameters passed to the current frame, in a recursive manner, you can observe this parameter decreasing.</p>

<p>Mostly all Information you want about the stack is also accessible from the <em>frame</em> objects that you can get as I've brought above.</p>

python recursion