You can use the built-in function inspect.currentframe().f_code.co_name
to get the name of the current function in Python.
import inspect
def my_function():
print(inspect.currentframe().f_code.co_name)
my_function() # prints "my_function"
This will return the name of the function as a string.
You can also use inspect.stack()[1][3]
to get the name of the current function.
import inspect
def my_function():
print(inspect.stack()[1][3])
my_function() # prints "my_function"
You can use the built-in sys._getframe()
function to get the current frame in Python, and then access the f_code
attribute to get the name of the current function.
import sys
def my_function():
print(sys._getframe().f_code.co_name) my_function() # prints "my_function"
This method is not recommended, because sys._getframe()
is an implementation detail and might not exist in all implementations of Python and also it's not recommended to use sys._getframe()
as it is not a part of the public python api and it's not guaranteed to be present in all python implementations.
You can also use the function.__name__
def my_function():
print(my_function.__name__) my_function() # prints "my_function"
It will give you the name of the function which is calling it.
0 댓글