Find function name in function
Terry Reedy
tjreedy at udel.edu
Tue May 20 18:39:11 EDT 2003
"Sean Ross" <frobozz_electric at hotmail.com> wrote in message
news:badusu$3fi$1 at driftwood.ccs.carleton.ca...
> 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.
As I pointed out in my first response to the OP, functions do not
necessarily have a 'called-by' name.
# revised be removing blank lines so cut and paste works
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()
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.
Terry J. Reedy
More information about the Python-list
mailing list