Home  >  Article  >  Backend Development  >  How Can I Get a Function\'s Name as a String in Python?

How Can I Get a Function\'s Name as a String in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 21:05:12731browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn