Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of the current method/function in Python

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?

like image 624
Shiva Krishna Bavandla Avatar asked Oct 27 '25 09:10

Shiva Krishna Bavandla


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!