Name of function within the function?

Andrew Csillag Andrew.Csillag at p98.f112.n480.z2.fidonet.org
Thu Jul 1 14:31:27 EDT 1999


From: Andrew Csillag <andrew at starmedia.net>

"Dula, Debbie (EXCHANGE:RICH2:2C25)" wrote:
> 
> I've looked and looked, but can't find the answer to this ... I'm
> sure it's right in front of me ...
> 
> I want the current function's name to be output in my error
> messages, but can't figure out how a function can get its own name
> (without already knowing it).  For example,
> 
>         def f1():
>                 print "Error in function", f1.__name__
> 
> is not really useful for what I need as I might as well print "Error
> in function f1".  Is there any generic way I can get the current
> function's name?
> 
> Thanks,
> Debbie

How's about this:
import sys
def y():
    print callerFunc()
def y2():
    print callerFunc()

def callerFunc():
    try:
        raise "arg"
    except "arg":
        func=sys.exc_traceback.tb_frame.f_back.f_code.co_name
    return func

y()
y2()

Should print:
y
y2

Cheers,
Drew Csillag
-- 
  Writing perl programs is like pounding stakes into your feet:
  You could if you had to, but would be better off if you didn't.
Corallary:
  Using Microsoft products is like pounding stakes into your feet:
  You could if you had to, but would be better off if you didn't.




More information about the Python-list mailing list