Sobes.tech
Junior — Middle

How can you preserve the documentation view of a function if it is wrapped by a decorator?

sobes.tech AI

Answer from AI

When wrapping a function with a decorator in Python, the original function's documentation (docstring) is lost because the decorator returns a new function. To preserve the docstring and other metadata, the functools.wraps function is used.

Example:

import functools

def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # additional logic
        return func(*args, **kwargs)
    return wrapper

@decorator
def my_function():
    """This is the function's documentation."""
    pass

print(my_function.__doc__)  # Outputs: This is the function's documentation.

functools.wraps copies the name, module, docstring, and other attributes of the original function to the wrapper, preserving documentation and debugging convenience.