Determine function name from within that function (without using traceback)

Rob picture Rob · Feb 21, 2011 · Viewed 275.1k times · Source

In Python, without using the traceback module, is there a way to determine a function's name from within that function?

Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar's name? Or better yet, foo.bar's name?

#foo.py  
def bar():
    print "my name is", __myname__ # <== how do I calculate this at runtime?

Answer

Andreas Jung picture Andreas Jung · Feb 21, 2011
import inspect

def foo():
   print(inspect.stack()[0][3])
   print(inspect.stack()[1][3]) #will give the caller of foos name, if something called foo