"What is the name of the function/method that called me?"

Michael Hudson mwh21 at cam.ac.uk
Fri Oct 15 10:57:18 EDT 1999


rturpin at my-deja.com writes:

> Given Python's run-time typing and the ability to generate call stacks
> of line numbers and module names, I suspect there is a way to answer
> this question, but it has escaped my perusal of my books and the online
> documentation.  Help appreciated.
> 
> Russell
> 
> PS to previous discussion:  I now use re's less, and string functions
> more.

There may be clearer and more succinct ways of writing it, but they
all do roughly this:

def whocalled():
    import sys
    try:
        raise ""
    except:
        return sys.exc_traceback.tb_frame.f_back.f_back.f_code.co_name

def test():
    def f():
        return whocalled()
    def g():
        def h():
            return whocalled()
        return h()
    print f(), "was the caller"
    print g(), "was the caller this time"

so in a function whocalled() returns the name of the function that
called the function calling whocalled(). Confused? Good.

insert-standard-disclaimer-about-poking-at-internals-ly y'rs
Michael




More information about the Python-list mailing list