How to Get the Name of a Function in Python?

In this tutorial, I will teach you how to get the name of a function in Python. As a Python developer working on various projects for clients across the USA. I came across a scenario where I needed to get the name of the function while debugging the code. Let us learn more about this topic with examples and screenshots.

Get the Name of a Function in Python

Let us learn some important methods to get the name of a function in Python.

Read How to Use the Mean() Function in Python?

1. Use the __name__ Attribute

The simplest way to get the name of a function in Python is by using the __name__ attribute. Every function in Python has this attribute, which stores the name of the function as a string.

Example

Let’s consider a scenario where we have a function that processes data for California residents:

def process_california_data():
    # Function logic here
    pass

print(process_california_data.__name__)

Output:

process_california_data

You can see the output in the screenshot below.

Get the Name of a Function in Python

As shown, the __name__ attribute returns the name of the function as a string.

Check out How to Use Default Function Arguments in Python?

2. Use the inspect Module

The inspect module in Python provides several useful functions to get information about live objects, including functions. We can use inspect.currentframe() to get the current frame and then extract the function name from it.

Example

Suppose we have a function that handles New York state tax calculations:

import inspect

def calculate_new_york_tax():
    frame = inspect.currentframe()
    function_name = frame.f_code.co_name
    print(function_name)

calculate_new_york_tax()

Output:

calculate_new_york_tax

You can see the output in the screenshot below.

How to Get the Name of a Function in Python

In this example, inspect.currentframe() gets the current stack frame, and frame.f_code.co_name retrieves the name of the function.

Read How to Exit a Function in Python?

3. Use Decorators to Log Function Names

Decorators can be a powerful tool to automatically log function names whenever they are called. This can be particularly useful for debugging and monitoring purposes.

Example

Let’s create a decorator that logs the function names for a series of functions related to Texas data processing:

def log_function_name(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_function_name
def process_texas_data():
    # Function logic here
    pass

@log_function_name
def analyze_texas_statistics():
    # Function logic here
    pass

process_texas_data()
analyze_texas_statistics()

Output:

Calling function: process_texas_data
Calling function: analyze_texas_statistics

You can see the output in the screenshot below.

Get the Name of a Function in Python Decorators

In this example, the log_function_name decorator logs the name of the function each time it is called.

Check out How to Call a Function Within a Function in Python?

Get Function Names Dynamically

In some cases, you might need to get the function name dynamically, such as when iterating over a list of functions. This can be achieved by accessing the __name__ attribute within a loop.

Example

Consider a scenario where we have multiple functions for different states and we want to print their names:

def process_california_data():
    pass

def process_texas_data():
    pass

def process_florida_data():
    pass

functions = [process_california_data, process_texas_data, process_florida_data]

for func in functions:
    print(func.__name__)

Output:

process_california_data
process_texas_data
process_florida_data

In this example, we iterate over a list of functions and print their names using the __name__ attribute.

Read How to Implement and Use the hash() Functions in Python?

Application: Log Function Execution

Let’s put everything together in a practical example where we log the execution of various functions in a data processing pipeline for different states.

Example

import inspect

def log_function_execution(func):
    def wrapper(*args, **kwargs):
        frame = inspect.currentframe().f_back
        function_name = frame.f_code.co_name
        print(f"Executing function: {function_name}")
        return func(*args, **kwargs)
    return wrapper

@log_function_execution
def process_california_data():
    print("Processing California data...")

@log_function_execution
def process_texas_data():
    print("Processing Texas data...")

@log_function_execution
def process_florida_data():
    print("Processing Florida data...")

process_california_data()
process_texas_data()
process_florida_data()

Output:

Executing function: process_california_data
Processing California data...
Executing function: process_texas_data
Processing Texas data...
Executing function: process_florida_data
Processing Florida data...

In this example, the log_function_execution decorator logs the function name each time a function is called, providing useful information for monitoring and debugging.

Check out How to Use the map() Function in Python?

Conclusion

In this tutorial, I explained how to get the name of a function in Python. I discussed three methods to accomplish tasks such as using the _name_attribute , using the inspect module , and using decorators to log function names. I also discussed how to get function names dynamically and in real-world applications with examples.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.