Let’s say I have a Python function f and fhelp. fhelp is designed to call itself recursively. f should not be called recursively. Is there a way for f to determine if it has been called recursively?
Let’s say I have a Python function f and fhelp . fhelp is designed
Share
Use the traceback module for this:
So, if any entry in the stack indicates that the code was called from
f, the call was (in)directly recursive. Thetraceback.extract_stackmethod gives you an easy access to this data. Theif len(l[2] ...statement in the example below simply counts the number of exact matches of the name of the function. To make it even prettier (thanks to agf for the idea), you could make it into a decorator: