Accessing method object from within a method

V

Vivek Sawant

Hi,

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

Thanks.
\vivek
 
P

Peter Hansen

Vivek said:
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
 
V

Vivek Sawant

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
 
P

Peter Hansen

Vivek said:
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?

That's about it. By referring to frame objects, I meant to lead you to
the stuff which you found so that you could see the extent of information
aside from just function name, which is available to you. Enjoy! :)

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top