3

For now, I got two ways to fetch the name of the current function/method in python

Function based

>>> import inspect
>>> import sys
>>> def hello():
...     print(inspect.stack()[0][3])
...     print(sys._getframe(  ).f_code.co_name)
...
>>> hello()
hello
hello

Class based

>>> class Hello(object):
...     def hello(self):
...         print(inspect.stack()[0][3])
...         print(sys._getframe(  ).f_code.co_name)
...
>>> obj = Hello()
>>> obj.hello()
hello
hello

Any other ways which are more easier and efficient than this?

Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313
  • 3
    Please don't post images of code in your questions, include it as text instead. – Thierry Lathuille Sep 10 '19 at 07:54
  • 1
    @ThierryLathuille Yeah that's a point, it makes easier for people to try the code directly copying it. – Shiva Krishna Bavandla Sep 10 '19 at 07:57
  • 2
    Does this answer your question? [Determine function name from within that function (without using traceback)](https://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback) – Greenonline Apr 14 '21 at 12:37
  • From the linked question's answers a good compromise (speed, not using private names) is `inspect.currentframe().f_code.co_name`. You will find also other methods there. They either use the function's identifier or change the way the function is called (e.g. using a decorator). – pabouk - Ukraine stay strong Jun 03 '22 at 22:26

1 Answers1

4

I believe that this post answers your problem: Determine function name from within that function (without using traceback)

There are no built-in ways to get the function's name. Glancing over your code I believe those are the easiest you will encounter.

I may be wrong though, feel free to correct me.