Course contentsShow
← Python
Lesson 337 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Ensuring Function Metadata Integrity

You will use wraps to preserve docstrings and signatures when creating decorators or functional wrappers for your iteration tools.

In this lesson, you will learn how to preserve a function’s original identity—like its name and docstring—when wrapping it inside a decorator.

When you create a decorator to add functionality to a function, you are technically replacing the original function with a new "wrapper" function. If you inspect the resulting function (using tools like help() or by checking .__name__), you’ll find that Python reports the metadata of the wrapper, not the original function. This can make debugging and documentation generated by automated tools very confusing.

To solve this, Python provides @functools.wraps. By applying this decorator to your inner wrapper function, you instruct Python to copy the metadata from the original function onto the wrapper.

Keeping Metadata Intact

Consider this example where we create a simple logger for a data processing function:

from functools import wraps

def log_iteration(func):
    @wraps(func)  # This preserves the original metadata
    def wrapper(*args, **kwargs):
        print(f"Calling: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_iteration
def process_data(data):
    """Processes a list of numbers."""
    return [x * 2 for x in data]

print(process_data.__name__)  # Prints: process_data (instead of 'wrapper')
print(process_data.__doc__)   # Prints: Processes a list of numbers.

Without @wraps(func), calling process_data.__name__ would return "wrapper", and the docstring would be lost entirely. By using wraps, you ensure that your code remains self-documenting and that your iterative tools or pipeline logic can correctly identify the functions they are manipulating.

This is particularly important when building complex generator pipelines or functional decorators, as it allows tools like help() to remain useful even after multiple layers of wrapping. Always use @wraps whenever you are creating functional decorators to keep your code’s metadata honest and accessible.

Key Takeaway: Always apply @functools.wraps to your wrapper functions within decorators to ensure your original function’s name, docstring, and signature remain intact and discoverable.