"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Get a Function\'s Name from Inside the Function in Python?

How to Get a Function\'s Name from Inside the Function in Python?

Published on 2024-12-21
Browse:146

How to Get a Function\'s Name from Inside the Function in Python?

Accessing Function Names from Within Functions

In Python, determining a function's name from within the function itself can be useful in situations where dynamic introspection is required.

The inspect module provides a convenient mechanism for obtaining information about a running program's code. Using inspect.stack(), we can access a list of frames representing the current call stack.

For a given function, the first frame in the stack list corresponds to the current function, while the second frame represents its caller. To access the function name, we can extract the third element of the first frame in the stack using inspect.stack()0.

Here's an example:

import inspect

def foo():
    print("my name is", inspect.stack()[0][3])

foo()

This code will print:

my name is foo
````
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3