|
Description:
You want to determine the name of the currently running function, e.g. to create error messages that don't need to be changed when copied to other functions. Function _getframe of module sys does this and much more.
Source: Text Source
import sys
this_function_name = sys._getframe().f_code.co_name
this_line_number = sys._getframe().f_lineno
this_filename = sys._getframe().f_code.co_filename
def whoami():
import sys
return sys._getframe(1).f_code.co_name
me = whoami()
def callersname():
import sys
return sys._getframe(2).f_code.co_name
him = callersname()
Discussion:
Inspired by Recipe 10.4 in O'Reilly's Perl Cookbook. Python's sys._getframe(), new in 2.1, offers information equivalent to Perl's builtin caller(), __LINE__ and __FILE__. If you need this for older Python releases, see recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52315, "Obtaining the name of a function/method".
|