SyntaxStudy
Sign Up
Python Preserving Metadata with functools.wraps
Python Intermediate 3 min read

Preserving Metadata with functools.wraps

functools.wraps

Decorators replace the wrapped function. Use @functools.wraps(func) to preserve the original function's name, docstring, and other attributes.

Example
import functools

def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def greet():
    """Say hello."""
    return "Hello"

print(greet.__name__)  # greet (not wrapper)
Pro Tip

Always use @functools.wraps in production decorators.