Name of current method

Benno benjl at cse.unsw.edu.au
Thu Nov 28 19:06:44 EST 2002


Thomas Guettler <pan-newsreader at thomas-guettler.de> wrote in message news:<pan.2002.11.28.20.26.03.172820.727 at thomas-guettler.de>...
> Hi!
> 
> How can I get the name of the method which is
> executed?
> 
> Example:
> 
> def mymethod(self):
> 	print self.__magic__
> 
> --> "mymethod"

Of course this is really evil, and only works in CPython (afaik), but here goes:

"""
import sys

def get_fn_name():
	return sys._getframe().f_back.f_code.co_name

def random_fn():
	print get_fn_name()

random_fn()
"""

sys._getframe() returns the current frame object.
f_back is a link to the frame object one high in the stack, which 
is the frame object of the calling function.
f_code is an object which basically describes the function related
to the current frame.
co_name is the name of the function.

I'm fairly sure this *isn't* a documented interface, (the '_' pretty much
indicates that), so it might not work in other implementation of python
or future versions of python.

If you want to hack some more do things like:

print dir(sys._getframe()) 
print dir(sys._getframe.f_code)

To have a look at what other interesting information you can get out
of the objects.

Benno



More information about the Python-list mailing list