Accessing method object from within a method

Vivek Sawant vivek_sawant at killspam.unc.edu
Wed Feb 18 17:05:13 EST 2004


Peter,

I had browsed through documentation for frame objects earlier, but 
nothing had jumped out. Here's what your suggestion helped me conjur up 
and it worked:

def method (self, ...)
   mname = sys._getframe(0).f_code.co_name;
   # do something with mname

Is this what you had in mind or did you mean to suggest something better?

Thanks!
\vivek


Peter Hansen wrote:

>Vivek Sawant wrote:
>  
>
>>Is there a way to obtain the method/function object from within the
>>method like 'self' refers to the object instance. I would like to avoid
>>looking method name (string) in class/object attributes. My goal is to
>>write code that need not be changed when the method name is changed.
>>
>>def method (self, ...)
>>   # somehow obtain 'methodobj' for this 'method'
>>   mname = methodobj.__name__;
>>   # do something with mname
>>    
>>
>
>The usual use for this is for debugging purposes, when somebody wants
>to print the name of the current method.  If your needs are not much
>different than that, look into sys._getframe() and frame objects.
>
>-Peter
>  
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20040218/5f91027c/attachment.html>


More information about the Python-list mailing list