Course contentsShow
← Python
Lesson 609 of 1,06010. Advanced Language FeaturesFree lesson

Preserving Metadata with functools wraps

Use the wraps decorator to ensure that decorated functions retain their original name, docstrings, and parameter signatures during introspection.

In this lesson, you will learn how to prevent your custom decorators from "hiding" the essential identity of the functions they wrap.

The Metadata Problem

When you write a decorator, you are essentially replacing your original function with a new wrapper function. While this is great for adding behavior, it creates a side effect: your original function loses its identity. If you try to check my_func.__name__ or read my_func.__doc__, you will see the metadata of the wrapper instead of the original function.

This is a major headache for debugging, introspection, and automated documentation tools, which rely on the __name__ and __doc__ attributes to describe your code.

The Solution: @functools.wraps

Python’s functools module provides a decorator called wraps designed specifically to solve this. When you apply @functools.wraps(func) to your wrapper function, it automatically copies the metadata—such as the name, docstring, and module—from the original function to the wrapper.

Here is how you implement it:

import functools

def debug(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@debug
def greet(name):
    """Greets the user by name."""
    return f"Hello, {name}!"

# Without @wraps, this would print 'wrapper'
print(greet.__name__)  
# Without @wraps, this would be empty
print(greet.__doc__)   

Why It Matters

By using @functools.wraps, you ensure that the decorated function is indistinguishable from the original for introspection tools. Even your IDE’s "hover-over" tooltips will correctly display the original function’s signature and documentation instead of showing you the internal implementation details of your wrapper.

It is considered a best practice to always use @functools.wraps when building decorators to maintain code clarity and ensure that your system’s diagnostic information remains accurate and reliable.

Key Takeaway: Always use @functools.wraps in your decorators to ensure that the original function's name, docstring, and signature remain accessible to the rest of your application.