Python – Get current function and parent function

When troubleshooting a fairly complex Python script I tend to find it a massive headache when working out the flow of the functions. What function am I currently in? What function called it etc. Looking through the docs I finally discovered the inspect module.

By making the following two functions;

def returnFunction():
return inspect.stack()[1][3]
def returnParent():
return inspect.stack()[2][3]

I can now call these from within my logger.debug lines and output the current function and parent function (the one that called the current function), all as soon as it executes.

An example;

logger.debug(“currentFunction=\”%s\” parentFunction=\”%s\””,returnFunction(),returnParent())

Leave a Reply

Your email address will not be published. Required fields are marked *