Identifying Caller

Robin Becker robin at jessikat.fsnet.co.uk
Sun Oct 12 06:53:13 EDT 2003


In article <mailman.28.1065950882.2192.python-list at python.org>, Tonguç
Yumruk <trooper at ttnet.net.tr> writes
>Is there a way to identify the caller of a function? For example:
>
>def foo():
>       print <Caller Functions name>
>
>def bar():
>       foo()
>
>I want foo to print "bar"... And it will be great if I can also detect
>call is came from which module.
>
>Thanks.
>
try something like this

#############################
def who_called_me(n=0):
        import sys
        f = sys._getframe(n)
        c = f.f_code
        return c.co_filename, c.co_name, f.f_lineno

if __name__=='__main__':
        def test2():
                print 'test2',who_called_me(1)

        def test1():
                print 'test1',who_called_me(1)
                test2()

        def test():
                print 'test',who_called_me(1)
                test1()
                test2()

        class dingo:
                def __init__(self):
                        self.a = 1
                        print '__init__',who_called_me(1)
                def doit(self):
                        print 'dingo.doit',who_called_me(1), self.a
                def calldoit(self):
                        print 'dingo.calldoit',who_called_me(1), self.a
                        self.doit()
                        test()
        def mongo():
                print 'mongo', who_called_me(1)
                d=dingo()
                d.doit()
                d.calldoit()
        test()
        test1()
        test2()
        mongo()
-- 
Robin Becker




More information about the Python-list mailing list