Determine function name from within that function (without using traceback)
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 Determine Function Name From Within That Function (Without Using Traceback)
00:26 Answer 1 Score 596
00:38 Accepted Answer Score 296
01:21 Answer 3 Score 55
01:41 Answer 4 Score 76
01:57 Thank you
--
Full question
https://stackoverflow.com/questions/5067...
--
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.