1

How do I print or show the recursive stack in Python when I'm running a recursive function?

3
  • 3
    What stack do you mean? could you explain you question a bit more? Commented Sep 13, 2016 at 7:19
  • Every time a recursive function is called, the language builds a stack of the result... Does this make sense? Commented Sep 13, 2016 at 16:53
  • @AAA I've updated my answer below, please see if there's anything else you have in mind that you can't access through frames. Commented Sep 19, 2016 at 6:07

1 Answer 1

4

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 inspect module.

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)

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.