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

Robin Becker robin at jessikat.demon.co.uk
Fri Oct 15 10:51:45 EDT 1999


In article <7u7bph$hvt$1 at nnrp1.deja.com>, 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.
>
>
>Sent via Deja.com http://www.deja.com/
>Before you buy.
someone posted this a while back


from sys import exc_info
def _tb():
        return exc_info()[2]
        
def who_called_me(n=0):
        try:
                raise None
        except:
                f = _tb().tb_frame.f_back
                while n>0:
                        t = f.f_back
                        if not hasattr(t,'f_code'): break
                        f = t
                        n = n - 1
                c = f.f_code
                return c.co_filename, c.co_name, f.f_lineno

if __name__=='__main__':
        import sys
        def test():
                print who_called_me()
        def test1():
                print who_called_me(1)
        def test2():
                print who_called_me(2)
        test()
        test1()
        test2()

-- 
Robin Becker




More information about the Python-list mailing list