Home > Article > Backend Development > How Can I Get a Function\'s Name as a String in Python?
Accessing Function Names as Strings
Retrieving a function's name as a string can be useful in various scenarios. This code demonstrates how to accomplish this:
def foo(): pass print(foo.__name__) # Output: foo
The preferred method is to use __name__, which works consistently across different types of functions:
import time print(time.time.__name__) # Output: time
Unlike func_name, which is not available for built-in functions:
print(time.time.func_name) # AttributeError
The double underscores in __name__ indicate its special nature, and it provides a uniform attribute for accessing names across classes, modules, and functions.
The above is the detailed content of How Can I Get a Function\'s Name as a String in Python?. For more information, please follow other related articles on the PHP Chinese website!