4

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?

4
  • 4
    Please don't post images of code in your questions, include it as text instead. Commented Sep 10, 2019 at 7:54
  • 1
    @ThierryLathuille Yeah that's a point, it makes easier for people to try the code directly copying it. Commented Sep 10, 2019 at 7:57
  • 2
    Does this answer your question? Determine function name from within that function (without using traceback) Commented Apr 14, 2021 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). Commented Jun 3, 2022 at 22:26

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.