Question: Traceback information from sys.exc_info()

Alex Martelli alex at magenta.com
Wed Aug 16 17:27:22 EDT 2000


"Donn Cave" <donn at u.washington.edu> wrote in message
news:8nemn7$i84o$1 at nntp6.u.washington.edu...
> Quoth "Brian Geddes" <brian.j.geddes at intel.com>:
    [snip]
> | On a closely related subject, I'm also trying to figure out a way to get
at
> | the name of the current function being executed, while still inside of
that
> | function.  I know this information must be stored by the interpreter
> | somewhere...I just don't know how to get at it.
    [snip]
> But tracebacks are relative to the handler, so this technique won't work
> to make a function that returns the name of its caller, you have to
> force the exception right there.  There may be another approach that
> would support a more convenient whoami() function.

Try:

def a2():
    stack = traceback.extract_stack()
    stack.reverse()
    level = 0
    print 'function',
    for file, line, func, stmt in stack:
        if func=='?': break
        if level:
            print 'called by %s' % (repr(func),),
        else:
            print 'function %s' % (repr(func),),
            level=1

Or to put it more conveniently, perhaps:

import traceback

def caller(n=1):
    stack = traceback.extract_stack()
    return stack[-n-2][2]

def a():
    b()

def b():
    c()

def c():
    print 'I am',caller(0)
    print 'called by',caller(1)
    print 'called by',caller(2)

a()

where caller(0) is the whoami() you want, caller(1)
or caller() is the caller of the function that calls
caller, etc.  In other words, the output is

I am c
called by b
called by a


Alex







More information about the Python-list mailing list