How to get the method/function which called a function?

Fredrik Lundh fredrik at pythonware.com
Wed Jul 24 13:15:47 EDT 2002


Chris Liechti wrote:

> >> a.t() # prints "<bound method A.t of <__main__.A instance at
> >> 0x805bb64>> a message"
>
> >> How can I implement the "GET_CALLER()" function in "log()" ?
> >
> > You can't.
>
> sure you can get the name of the calling function. its printed when a
> exception is thrown, isn't it? ;-)

but he wasn't asking for the name, he was asking for the
bound method object.

if all you need is the name, you can do:

    caller = sys._getframe(1).f_code.co_name

or perhaps

    def GET_CALLER():
        return sys._getframe(2).f_code.co_name

    ...

    caller = GET_CALLER()

(this gives the name used in the "def" statement that created
the code object, not the name used to access the function or
method.  they're usually the same, though...)

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list