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

Linda Hamilton
Release: 2024-11-26 21:05:12
Original
730 people have browsed it

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
Copy after login

The preferred method is to use __name__, which works consistently across different types of functions:

import time

print(time.time.__name__)  # Output: time
Copy after login

Unlike func_name, which is not available for built-in functions:

print(time.time.func_name)  # AttributeError
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template