How do I print or show the recursive stack in Python when I'm running a recursive function?
-
3What stack do you mean? could you explain you question a bit more?Masked Man– Masked Man2016-09-13 07:19:13 +00:00Commented 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?AAA– AAA2016-09-13 16:53:47 +00:00Commented 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.Ali– Ali2016-09-19 06:07:49 +00:00Commented Sep 19, 2016 at 6:07
Add a comment
|
1 Answer
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.