Get the name of a function

Chris Rebert clp2 at rebertia.com
Fri Aug 5 23:19:21 CEST 2011


On Fri, Aug 5, 2011 at 11:52 AM, gervaz <gervaz at gmail.com> wrote:
> Hi all, is there a way to retrive the function name like with
> self.__class__.__name__?
>
> Using self.__dict__.__name__ I've got
>
>>>> def test():
> ...     print(self.__dict__.__name__)
> ...

Er, where did `self` magically come from?

>>>> test
> <function test at 0x0178DDF8>
>
> But I really just want the function name, so 'test'
>
> Any help?

Courtesy of the "Observations on the three pillars of Python execution" thread:

from inspect import currentframe

def foobar():
    my_name = currentframe().f_code.co_name
    print(my_name)

I would recommend against a function knowing its own name though,
unless it's for debugging or necessary metaprogramming purposes.

Cheers,
Chris



More information about the Python-list mailing list