Programming
python function introspection traceback
Updated Sun, 24 Jul 2022 23:28:00 GMT

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


In Python, without using the traceback module, is there a way to determine a function's name from within that function?

Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar's name? Or better yet, foo.bar's name?

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



Solution

Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar" or bar.__name__ depending on context.

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.





Comments (5)

  • +0inspect.currentframe() is one such way. — Sep 20, 2014 at 10:47  
  • +0 – Combining @CamHart's approach with @Yuval's avoids "hidden" and potentially deprecated methods in @RoshOxymoron's answer as well as numerical indexing into the stack for @neuro/@AndreasJung's answer: print(inspect.currentframe().f_code.co_name) — Mar 17, 2015 at 21:43  
  • +3 – is it possible to summarize why its been rejected? — Jun 15, 2017 at 18:27  
  • +0 – why is this the chosen answer? Question isn't about accessing the current function or the module itself, just the name. And the stacktrace/debugging features already have this information. — Apr 03, 2019 at 11:23  
  • +0 – As of today, tested within my CPython 3.7.2 bar.__name__ does work. For the simplest unaccepted answer for Python 3.x + see Vagiz Duseev's answer below Answer. — May 23, 2021 at 13:29  


External Links

External links referenced by this document: