Name of current method

Mark Rowe bdash at gmx.net
Fri Nov 29 00:57:55 EST 2002


On Friday, Nov 29, 2002, at 13:06 Pacific/Auckland, Benno wrote:
>
> 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()
> """

A slightly cleaner method is to use the traceback module.

"""
import traceback

def get_fn_name():
     return traceback.extract_stack(limit=2)[0][2]

def random_fn():
     print get_fn_name()

random_fn()
"""

traceback.extract_stack(limit=2) returns a list of the top two stack 
frames, each represented as a tuple in the form (filename, line number, 
function name, text)

Mark





More information about the Python-list mailing list