I am debugging some complicated legacy Python3 code and find myself needing to know, at a particular point in the executing code, all the try
blocks that are active in the call stack. Is there a way to introspect and print out the nested tree?
So, for example, we might have this code:
def fn1():
try:
fn2()
except IOError:
# do something
def fn2():
try:
fn3()
except NameError:
# do something
def fn3():
print( **YourAnswerHere** )
The idea is that if I invoke fn1()
then the print statement in fn3
would produce something like:
fn1: try / except IOError
fn2: try / except NameError
If that’s not possible, I’d be able to get along if it merely printed [fn1 fn2]
. Ideally it would handle try / finally
blocks as well.
I could find nothing about this using Google. I looked at every occurrence of the word try
in the documentation for Python’s inspect
and traceback
modules but found nothing. The ast
module has classes related to try
but I don’t have a clue how to use them and it looks like those are for analyzing static code, rather than executing code. Thank you.