Finding the calling method

Peter Hansen peter at engcorp.com
Tue Jan 14 21:54:49 CET 2003


Mark wrote:
> 
> I don't know if you there is a function or method you can call to find
> this.  Inside a method(method A) I'm calling another method(method B)
> inside the same class.  Is there a way while I'm inside method B to
> find out what method called it, which would be method A.  Do I have to
> look at the stack or is there a function to call?

In Python since 2.1, sys._getframe(1) will return the calling frame,
from which you can extract the name of the method.  You can also learn
about the 'inspect' standard module from the docs.

>>> class A:
...   def methA(self):
...     self.methB()
...   def methB(self):
...     import sys
...     print 'I am called by',sys._getframe(1).f_code.co_name
...
>>> a = A()
>>> a.methA()
I am called by methA

-Peter




More information about the Python-list mailing list