Find function name in function

Sean Ross frobozz_electric at hotmail.com
Tue May 20 20:33:54 EDT 2003


"Terry Reedy" <tjreedy at udel.edu> wrote in message news:4U-
> >>> XXX()
> XXX # verifies copy ok
> >>> fl=[XXX]
> >>> fl[0]()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in XXX
>   File "<stdin>", line 18, in whoami2
> IndexError: list index out of range
>
> I suppose you could wrap that line in try:except: and return '' in
> this case.  But the user had better be prepared for a null name.
>


Oddly enough, I don't get that error, however I do not the name I'm looking
for either, so for the time being I've added an else clause to the for loop.
Now, if I don't find the name, I return None so the user can tell that the
name was not found by checking for this condition.

def whoaminow():
    "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()
    sys.stdout = oldout  # restore stdout
    # retrieve current byte code line
    fd = open('log')
    for line in fd.xreadlines():
        if line.startswith('-->'):
            break
    else:
        line = None
    fd.close()
    # isolate function name
    if line:
        funcname = line.split()[-1][1:-1]
    else:
        funcname = None
    return funcname

# some testing...
def foo():
    me = whoaminow()
    return me

fl = [foo]
print fl[0]()

#outputs
None








More information about the Python-list mailing list