Accessing func_name from inside a function

Alex Martelli aleaxit at
Sun Mar 26 23:26:07 CEST 2006

James Thiele <jamesthiele.usenet at> wrote:

> I'd like to access the name of a function from inside the function. My
> first idea didn't work.
> >>> def foo():
> ...     print func_name
> ...
> >>> foo()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in foo
> NameError: global name 'func_name' is not defined

So, define it -- as a function, of course:

def func_name():
    import sys
    return sys._getframe(1).f_code.co_name

def foo():
    print func_name()

def bar():
    print func_name()

No doubt you'll object that the internals of func_name are "ugly", but
the point is that it can be hidden anywhere you like, so its internals
are as irrelevant as they would be if it was a built-in.


More information about the Python-list mailing list