[Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ?

Kent Johnson kent37 at tds.net
Sat Feb 13 19:57:21 CET 2010


On Sat, Feb 13, 2010 at 10:56 AM, patrice laporte <zepangolin at gmail.com> wrote:

> Being in an exeption of my own, I want to print the name of the caller, and
> I'm looking for a way to have it.
>
> I've found a lot of recipe all of them using what seems to be, according to
> me, a not so good trick : all those recipe make use of
> sys._getframe(1).f_code.co_name
>
> A closer look at the documentation about sys._getframe at
> http://docs.python.org/library/sys.html make me think it's not a good idea,
> because of the note :
> "CPython implementation detail: This function should be used for internal
> and specialized purposes only. It is not guaranteed to exist in all
> implementations of Python."
>
> So, this trick works today, but what about tomorow ?
>
> Is anybody have an idea how to get the the same result without _getframe ?

Here is a way to do it using the traceback module. Under the hood it
is still using implementation details contained in traceback and stack
frame objects but the public interface in the traceback module should
be stable.

import sys, traceback

def whoami():
    stack = traceback.extract_stack(limit=2)
    print "Who call me ? : ", stack[0][2]
    print "Who am I ? : ", stack[1][2]

def print_caller_name():
    whoami()

if __name__ == "__main__":
   print_caller_name()

Kent


More information about the Tutor mailing list