Spot any errors? let me know, but Unleash your pedant politely please.

Monday, 18 May 2009

Finding the name of the current function in Python. nameOfThisFunction()

As part of my testing, I need to create logs that give me some traceability for when things go wrong, evidence of testing whatever the result. Kind of like permanent debug text. I'll look at differences between log files of the same tests run on previous and new versions. It's ad-hoc testing when it's first written and it's regression testing thereafter.

One of the ways to show trace is simply to show which methods/functions are being called. Being lazy, I simply want to cut and paste something, I don't want to also have to change it. I would prefer to use the actual function name rather than hard coding into a string for printing / logging. The name might change in the future. I might forget to alter the name after pasting it.

This is what I don't want:

def testStepA(param):
    writeToLogFile('Reached function 'testStepA')
    ...

def testStepB(param):
    writeToLogFile('Reached function 'testStepB')
    ...

I want something like this instead:

def testStepA(param):
    writeToLogFile('Reached function '%s', nameOfThisFunction())
    ...

def testStepB(param):
    writeToLogFile('Reached function '%s', nameOfThisFunction())
    ...

Fortunately, inspect gives me the information I'm after:

import inspect

def nameOfThisFunction (offset=0):
    return inspect.stack()[1 + offset][3]

No comments:

Post a Comment