Ok, I’m looking to create a quick debug function that prints out the current function that is running (to help in debugging what functions are being run).  I know that I can use a debugger to get a stack trace (and I do), but I’m still curious about this problem.  Here’s what I’ve got so far:

                       

def Foo():

            PrintCurFunc()

                       

class cBase:

            def Run(self):

                        PrintCurFunc(self)

 

class cChild(cBase):

            pass

 

import traceback

def PrintCurFunc(obj = None):

            stack = traceback.extract_stack()

            scriptName, lineNum, funcName, lineOfCode = stack[-2]

            if obj:

                        print '%s.%s()' % (obj.__class__.__name__, funcName)

            else:

                        print '%s()' % funcName

 

def main():

            Foo()

            b = cBase()

            c = cChild()

            b.Run()

            c.Run()

            x = cTwo()

            x.Run()

           

if __name__ == '__main__':

            main()  

 

The output I get is:

 

Foo()

cBase.Run()

cChild.Run()

cTwo.Run()

cTwo.Run()

 

Now, PrintCurFunc() above gets me the output I want in the fist two cases (Foo() and cBase.Run()).  But, in the case of c.Run(), I would still like to see it output cBase.Run(), since that is the method that is being run.  Yes, cChild being derived from cBase does have an inherited Run method, but I would like my output to display “where the code physically lives” so that for debugging I can basically get a stack trace to see what is executed when.  It might be more clear in this example:

 

class cOne:

            def Run(self):

                        PrintCurFunc(self)

 

class cTwo(cOne):

            def Run(self):

                        PrintCurFunc(self)

                        cOne.Run(self)

x = cTwo()

x.Run()

 

gets me the output of:

cTwo.Run()

cTwo.Run()

 

when I would prefer it output:

cTwo.Run()

cOne.Run()

 

…which reflects the call stack more clearly.  Now, I’ve looked into the traceback module but was only able to find the name of the function.  Passing self into PrintCurFunc was my attempt at getting at the class name.  But, as you see, it obviously returns the object’s class name and not the class name the function was defined on.  I also looked at this recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 but it only gives me a function name and not the class name as well.

 

Any thoughts?  I’m a bit new to Python’s reflection features…

 

Thanks tons!

 

-Scott

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to