Alex Rivera | Logout

Determine function name from within that function

Asked 2011-02-21T15:11:36.230
794

Is there a way to determine a function's name from within the function?

def foo():
    print("my name is", __myname__)  # <== how do I calculate this at runtime?

In the example above, the body of foo will somehow access the function name "foo" without hard-coding it. The output would be:

>>> foo()
my name is foo
Edit
Report

1 Answer

55

You can get the name that it was defined with using the approach that @Andreas Jung shows, but that may not be the name that the function was called with:

import inspect

def Foo():
   print inspect.stack()[0][3]

Foo2 = Foo

>>> Foo()
Foo

>>> Foo2()
Foo

Whether that distinction is important to you or not I can't say.

answered 2011-02-21T15:34:31.333

Your Answer