Introducing functool.wraps
Swipe to show menu
When you write your own decorators, you often lose important information about the original function, such as its name, docstring, and module. This happens because the decorator replaces the original function with a new wrapper function. To fix this, use the functools.wraps decorator from Python's standard library.
By applying functools.wraps to your wrapper function, you preserve the original function's metadata. This means:
- The function's
__name__attribute remains the same as the original; - The function's
__doc__string is kept intact; - The
__module__attribute and other metadata are preserved.
Preserving metadata is important for debugging, documentation generation, and tools that rely on function introspection. Without functools.wraps, stack traces and help utilities may display confusing or incorrect information, making your code harder to maintain and debug.
1234567891011121314151617181920212223from functools import wraps # Define a decorator that will wrap another function def my_decorator(func): # Use @wraps to preserve metadata from the original function @wraps(func) def wrapper(*args, **kwargs): # This code runs before the original function print("Running the decorated function...") return func(*args, **kwargs) # Call the original function return wrapper # Return the wrapper as the new decorated function # Apply the decorator to a function def say_hello(): """Prints a hello message.""" print("Hello!") say_hello = my_decorator(say_hello) say_hello() # Print out the preserved metadata print(f"Function name: {say_hello.__name__}") # Name is preserved print(f"Docstring: {say_hello.__doc__}") # Docstring is preserved
You can see how to use functools.wraps to preserve the original function's metadata when creating a decorator. By applying functools.wraps to your wrapper, you ensure that attributes like the function's name and docstring are not lost after decoration.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat