Today, we will see the two most used methods to get a function name as a string in Python.
Using __name__ to get a function name as a string in Python
For user-defined functions
def I_am_function():
return 'nothing'
print(I_am_function.__name__)
Output:
I_am_function
For Class methods
class CopyAssignment(object):
def my_method(self):
pass
print(CopyAssignment.my_method.__name__)
Output:
my_method
For functions of modules
import time
print(time.time.__name__)
Output:
time
Using __qualname__ to get a function name as a string in Python
For user-defined functions
def I_am_function():
return 'nothing'
print(I_am_function.__qualname__)
Output:
I_am_function
For Class methods
class CopyAssignment(object):
def my_method(self):
pass
print(CopyAssignment.my_method.__qualname__)
Output:
CopyAssignment.my_method
For functions of modules
import time
print(time.time.__qualname__)
Output:
time
You can find more discussion on How to get a function name as a string in Python?
Thank you for visiting our website.