Sobes.tech
Middle

What is the purpose of the wraps decorator in Python?

sobes.tech AI

Answer from AI

# Import the wraps decorator
from functools import wraps

# Define a decorator that prints a message before and after the function execution
def simple_decorator(func):
    # Use wraps to preserve the metadata of the original function
    # Without wraps, information about decorated_function (name, docstring) will belong to wrapper_function
    @wraps(func)
    def wrapper_function(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper_function

# Applying the decorator to a function
@simple_decorator
def my_function(a, b):
    """This is the documentation for my_function."""
    return a + b

# Calling the decorated function
result = my_function(5, 3)

# Checking the function's metadata
# my_function.__name__ will be 'my_function' (thanks to wraps)
# my_function.__doc__ will be 'This is the documentation for my_function.' (thanks to wraps)
print(f"Function name: {my_function.__name__}")
print(f"Function docstring: {my_function.__doc__}")

The wraps decorator from the functools module is used to preserve the metadata (name, docstring, annotations, etc.) of the original function that is being wrapped by the decorator. Without wraps, the decorated function will have the metadata of the inner wrapper function. This is important for debugging, code introspection, and some tool operations.