Junior — Middle
Can you explain the role and usage of the @wraps decorator from the functools module in Python?
sobes.tech AI
Answer from AI
The @wraps decorator from the functools module is used to preserve the metadata of the original function when writing custom decorators.
When you create a decorator, it usually returns a new wrapper function that replaces the original function. Without @wraps, the function's name, documentation, and other attributes will be lost, making debugging and documentation more difficult.
Example of using @wraps:
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Before calling the function")
result = func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
@my_decorator
def greet(name):
"Greeting function"
print(f"Hello, {name}!")
print(greet.__name__) # Will output 'greet', not 'wrapper'
print(greet.__doc__) # Will output 'Greeting function'
Thus, @wraps helps to preserve the original function's attributes during decoration.