Advertisement
Intermediate Python, Decorators

Why should you use functools.wraps when writing a decorator, and what problem does it solve?

Short answer

Without @functools.wraps(func), the wrapper function REPLACES the original's __name__, __doc__, and other metadata with the WRAPPER's own — breaking introspection tools, debuggers, and documentation generators that rely on a function's real identity; wraps() copies that metadata…

Save Python mock interview
Advertisement
AModel answer
Without @functools.wraps(func), the wrapper function REPLACES the original's __name__, __doc__, and other metadata with the WRAPPER's own — breaking introspection tools, debuggers, and documentation generators that rely on a function's real identity; wraps() copies that metadata from the original function onto the wrapper.
import functools

def logged(func):
    @functools.wraps(func)  # preserves func's __name__, __doc__, etc.
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@logged
def add(a, b):
    """Adds two numbers."""
    return a + b

print(add.__name__)  # 'add', NOT 'wrapper', thanks to functools.wraps
Real-world example
Ensuring a decorated function still shows its real name and docstring in help(), IDE tooltips, and automated documentation.
Likely follow-ups
  • What specific attribute does functools.wraps ALSO preserve that lets you access the original undecorated function directly?
Related topics