Find function name in function

Sean Ross frobozz_electric at hotmail.com
Tue May 20 15:15:42 EDT 2003


Okay, here you go...This function will identify the called functions name by
it's proper name or by it's alias, however it's being called. It grabs the
frame where the function was called, gets the associated code object and
last instruction index, disassembles the code object, isolates the
instruction, and slices out the function name. I don't know if this is
robust, dangerous, or whatever, but it does what you're asking for.

def whoami2():
    "returns name of called calling function"
    import sys, dis

    # get frame where calling function is called
    frame = sys._getframe(2)

    # get code and next to last instruction from frame
    code = frame.f_code
    lasti = frame.f_lasti-3

    # redirect ouput of disassemble (stdout)
    oldout = sys.stdout
    sys.stdout = open('log','w')
    dis.disassemble(code, lasti)
    sys.stdout.close()

    # restore stdout
    sys.stdout = oldout

    fd = open('log')

    # retrieve current byte code line
    current = [line for line in fd.readlines() if line.startswith('-->')][0]
    fd.close()

    # isolate function name
    funcname = current.split()[-1][1:-1]
    return funcname

def XXX():
    print whoami2()

XXX()
yy=XXX
a= yy()
zz=XXX
zz()

print "%s %s"%(yy(), zz())


# OUTPUT
XXX
yy
zz
yy
zz
None None







More information about the Python-list mailing list