The Python Oracle

Determine function name from within that function (without using traceback)

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Question
00:36 Accepted answer (Score 276)
01:16 Answer 2 (Score 549)
01:31 Answer 3 (Score 255)
02:31 Answer 4 (Score 64)
02:56 Thank you

--

Full question
https://stackoverflow.com/questions/5067...

Accepted answer links:
[proposed]: http://www.python.org/dev/peps/pep-3130/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #function #introspection #traceback

#avk47



ANSWER 1

Score 596


import inspect

def foo():
   print(inspect.stack()[0][3])
   print(inspect.stack()[1][3])  # will give the caller of foos name, if something called foo

foo()

output:

foo
<module_caller_of_foo>



ACCEPTED ANSWER

Score 296


If you don't want to play with the stack yourself, you should either use "bar" or bar.__name__ depending on context.

Python doesn't have a feature to access the function or its name within the function itself. A magic __function__ had been proposed for Python 3.0 but rejected. See PEP 3130 – Access to Current Module/Class/Function.

The given rejection notice is:

This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.




ANSWER 3

Score 76


functionNameAsString = sys._getframe().f_code.co_name

I wanted a very similar thing because I wanted to put the function name in a log string that went in a number of places in my code. Probably not the best way to do that, but here's a way to get the name of the current function.




ANSWER 4

Score 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.