Getting method name from within the class method

Fredrik Lundh fredrik at pythonware.com
Thu Oct 19 08:33:10 CEST 2006


Gabriel Genellina wrote:

> I could see some merit on getting that info in an automatic way.
> The only reason I can see for knowing the name of a function is for 
> debugging purposes - maybe some kind of logging utility. If you are in 
> "debug mode", resources are not too important, but correct information 
> is. Imagine a logfile that says that you were at function_a but instead 
> you were at function_b (because of copy&paste without replacing the names)

imagine a log file that says that you're about to create a file when 
you're actually removing it (because of copy&paste without replacing the 
message).

focussing on function names when logging is pretty silly, anyway.  it's 
usually better to focus on that the code is actually doing, rather than 
internal artifacts.

but even if you want to output function names, it's of course better to 
put that functionality into the logging function itself:

     ##
     # Issues a log message.

     def log(fmt, *args):
         print who_called_me(2), "-", fmt % args

     ##
     # Returns the name of the calling function or method, if known.
     #
     # @param depth Stack depth.  Defaults to immediate caller.
     # @return The name of the calling function.

     def who_called_me(depth=1):
         return sys._getframe(depth).f_code.co_name

</F>




More information about the Python-list mailing list