How to get the name of a function in Python

Published on Aug. 22, 2023, 12:15 p.m.

To get the name of a function in Python, you can use the __name__ attribute of the function object. Here’s an example:

def my_function():
    pass

print(my_function.__name__)

This will output my_function, which is the name of the function.

Alternatively, you can use the inspect module to get the name of the current function. Here’s an example:

import inspect

def my_function():
    print(inspect.stack()[0][3])

my_function()

This will output my_function, which is the name of the current function. Note that this method can only be used to get the name of the current function, not any arbitrary function.

Tags:

related content