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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# use sys._getframe() -- it returns a frame object, whose attribute # f_code is a code object, whose attribute co_name is the name: import sys this_function_name = sys._getframe().f_code.co_name # the frame and code objects also offer other useful information: this_line_number = sys._getframe().f_lineno this_filename = sys._getframe().f_code.co_filename # also, by calling sys._getframe(1), you can get this information # for the *caller* of the current function. So you can package # this functionality up into your own handy functions: def whoami(): import sys return sys._getframe(1).f_code.co_name me = whoami() # this uses argument 1, because the call to whoami is now frame 0. # and similarly: def callersname(): import sys return sys._getframe(2).f_code.co_name him = callersname()
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".