On Sat, Feb 13, 2010 at 10:56 AM, patrice laporte <[email protected]> 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 _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
