Get the name of the current method/function in Python

17.6k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.