How to Get a Function Name as a String in Python?

Rate this post

Problem Formulation

Given a function object assigned to a name. How to get the name of the function as a string?

For example, consider the following function your_function. How to get the name "your_function" from this?

def your_function():

string_name = ???

Your desired value of the result stored in string_name is the string "your_function".

# your_function

Method 1: Use the __name__ Attribute

The most Pythonic way to extract the name from any object or class is to use its __name__ attribute. Attributes enclosed in double underscores (dunder attributes) provide special functionality to Python programmers. For example, calling your_function.__name__ yields the string value 'your_function'.

def your_function():

string_name = your_function.__name__

# your_function

However, there’s an important case where this method will fail.

ATTENTION: In Python, functions are objects. You can create multiple variables pointing to the same object in memory. Therefore, you could create two names func_1 and func_2 that both point to the same function object. When calling func_1.__name__ the result may be func_2 instead of func_1 what you expected.

This is showcased in the following minimal example:

def func_2():

func_1 = func_2
# func_2

As both names point to the same memory object, but func_2 was pointing to it first, the name of the object is func_2. The memory usage of this code is visualized using the Python Tutor tool:

Both variables refer to the same function object that defaults as func_2 name.

Method 2: Use the __qualname__ attribute

To extract the name from any object or class, you can also use its __qualname__ attribute. For example, calling your_function.__qualname__ yields the string value 'your_function'. You’d use __qualname__ over __name__ if you’d also need some context such as the class defining the method.

The following code creates a function and a method inside a class. It then compares the output of the __name__ and __qualname__ attributes for both the function and the class:

def my_function():

class My_Class(object):
    def my_method(self):

print(my_function.__name__)             # "my_function"
print(My_Class.my_method.__name__)      # "my_method"

print(my_function.__qualname__)         # "my_function"
print(My_Class.my_method.__qualname__)  # "My_Class.my_method"

You can dive deeper into the idiosyncrasies of __qualname__ here and here.

Thanks for reading this article. To boost your Python skills, consider joining the free Finxter email academy with plenty of cheat sheets, Python tutorials, and fun programming puzzles! πŸ™‚