faqts : Computers : Programming : Languages : Python : Common Problems

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 5 people (100%) answered Yes
Recently 4 of 4 people (100%) answered Yes

Entry

Is it possible to determine the name of the currently executing function?

Nov 19th, 2008 21:42
Chris Zate, unknown unknown, Alex Martelli


Sure -- piece o' cake...:
def caller(n=1):
    from traceback import extract_stack
    stack = extract_stack()
    return stack[-n-2][2]
# Example usage:
def a():
    print "this is", caller(0)
    b()
def b():
    print "and this is",caller(0),
    print "called by",caller()
Expected output by calling a():
http://animaux.leblogguide.com/
http://voyagesingapour.leblogguide.com
http://voyageauperou.leblogguide.com
http://voyageauchili.leblogguide.com
http://italiehotels.leblogguide.com
this is a
and this is b called by a