How to Get a Function Name as a String in Python
Created
Modified
Using __name__ Attribute
Using __qualname__ is the preferred method as it applies uniformly. It works on built-in functions as well:
#!/usr/bin/python3
def my_func():
pass
class A():
def getName():
pass
print(my_func.__name__)
print(A.getName.__name__)
# Python 3.3+
print(A.getName.__qualname__)
my_func getName A.getName
If you're interested in class methods too, Python 3.3+ has __qualname__ in addition to __name__.
Using inspect Module
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
See the following example:
#!/usr/bin/python3
# Import module
import inspect
def my_func():
func_name = inspect.currentframe().f_code.co_name
print(func_name)
pass
class A():
def getName():
func_name = inspect.currentframe().f_code.co_name
print(func_name)
pass
my_func()
A.getName()
my_func getName
sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.