Get name of current function and caller with Python

11 January, 2007 - 15:22
Categories:

With the python module inspect, one can inspect (no kidding) the run-time python stack. Among other things, this makes it possible to get the name of the current function or callers. Handy for logging or debugging purposes. A simple script to illustrate:

import inspect
# functions
def whoami():
    return inspect.stack()[1][3]
def whosdaddy():
    return inspect.stack()[2][3]
def foo():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
    bar()
def bar():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
johny = bar
# call them!
foo()
bar()
johny()

output:

hello, I'm foo, daddy is ?
hello, I'm bar, daddy is foo
hello, I'm bar, daddy is ?
hello, I'm bar, daddy is ?

How does it work?

  • inspect.stack() returns a list with frame records.
  • In function whoami(): inspect.stack()[1] is the frame record of the function that calls whoami, like foo() and bar().
  • The fourth element of the frame record (inspect.stack()[1][3]) is the function name.

The rest should be obvious (check the python docs on inspect for more information), except that johny() thinks he's function bar(). That's because johny actually just points to the code of bar() and the function name bar is associated with the code and not with the variables.

Inspiration:

19 November, 2009 - 20:06

Index for function name

DavidF (not verified)

I could be doing something completely wrong, but inspect.stack()[1][3] doesn't get me the function name, it has the value of ''.

(This is with Python 2.5) To get the name of the function, I used inspect.stack()[0][3].

2 December, 2009 - 14:14

If you use inspect.stack()

slippens

If you use inspect.stack() inside the function you want to investigate, you should indeed use index 0. In my example I used a function whoami(), which adds another function call layer, and I have to look at index 1.

1 November, 2009 - 08:21

Thanks so much!!!

Tyler Starke (not verified)

Dude, this totally injected awesome into my debugging. To say thanks here is this:

class TrueDebug(object):
    ### Alpha ###
    """A simple debugger. Add debug() to a function and it prints the function name and any objects included. 
    Adding True to locale prints the file name where the function is. Adding False to log turns the log off.
    This feature can be modified to trace deeper and find the bugs faster, ending the puzzle box."""
    def __init__(self, objects=None, locale=False, log=True, parents=False):
        if log == False: return
        current = inspect.currentframe()
        if parents: self.get_parents(current)
        self.true_debug(current, objects, locale)
 
    def true_debug(self, current, objects, locale):
        debug_string = 'Function: ' + str(inspect.getouterframes(current)[1][3])
        #if locale == 'all': print inspect.getouterframes(current)[4]; return
        if objects != None: debug_string += ' Objects: ' + str(objects)
        if locale: debug_string += ' File: ' + str(inspect.getouterframes(current)[1][1])
        print debug_string
        return
 
    def get_parents(self, current):
        debug_string = 'Function: ' + str(inspect.getouterframes(current)[1][3]) + ' Parents:'
        family = list(inspect.getouterframes(current))
        for parent in family:
            debug_string += ' ' + str(parent[4])
        print debug_string
        return
debug = TrueDebug

To call it you just import debug into any script then in your classes or functions run debug(). If you add something to the call, it will print out the the object you add. You can even add objects in parenthesis. Using log=False you can focus in on what you need debugged. This should help remove the puzzle box that can occur when you don't know where objects are changing.

You have to format it yourself.

1 October, 2008 - 02:26

There goes Stefaan... still

Charlie (not verified)

There goes Stefaan... still helpin' a brother out over a year and a half later.

Thanks, man.

30 July, 2008 - 04:15

Very cool

Ian Wagner (not verified)

Nice tutorial man :) Thanks for your contribution to the community!

2 September, 2008 - 09:33

That's exactly what I was

Anonymous (not verified)

That's exactly what I was looking for. Thank you :)

Post new comment

The content of this field is kept private and will not be shown publicly.
  • No HTML tags allowed
  • Lines and paragraphs break automatically.

More information about formatting options