functools.wraps is a decorator in Python that is used to preserve the metadata of the original function when it is wrapped by a decorator. When you create a decorator, the function that it returns (the wrapper function) typically loses the original function's name, docstring, and other attributes. By using @wraps(func) on the wrapper function, it copies the metadata from the original function func to the wrapper.
This is important for introspection and documentation purposes, as it allows tools and developers to access the original function's name, docstring, and annotations even after it has been decorated.
Here’s a simple example:
from functools import wraps
def my_decorator(func):
@wraps(func) # This preserves the metadata of func
def wrapper(*args, **kwargs):
print("Before calling the function")
return func(*args, **kwargs)
return wrapper
@my_decorator
def example_function():
"""This is an example function."""
pass
print(example_function.__name__) # Outputs: example_function
print(example_function.__doc__) # Outputs: This is an example function.
In this example, example_function retains its name and docstring even after being decorated with my_decorator.
