[Tutor] introspecting an object for method's name?

Tim Golden mail at timgolden.me.uk
Mon Oct 19 14:40:12 CEST 2009


Kent Johnson wrote:
> On Sunday, October 18, 2009, Serdar Tumgoren <zstumgoren at gmail.com> wrote:
>> Hi everyone,
>> I'm trying to create a generic logging function, and I'm able to get
>> at the name of the module and class using the built-in attributes
>> __module__, __class__, and __name__.
>>
>> But I wasn't sure how to also grab the name of the function or method,
>> so that when an error occurs, I can log the name of the failing method
>> as well.
> 
> Using sys._getframe() you can get the name of the current function or
> the name of the calling function. Getting the name of the caller means
> you can wrap your logger into a function. See this recipe:
> http://code.activestate.com/recipes/66062/

Or just use the built-in logging module which lets you specify
the containing function name as one of its formatting keywords:

http://docs.python.org/library/logging.html#formatter-objects

TJG


More information about the Tutor mailing list