Home >Backend Development >Python Tutorial >How Does `functools.wraps` Preserve Original Function Attributes in Python Decorators?
Understanding functools.wraps
In Python programming,decorators are commonly used to add functionality to functions. However, usingdecorators can sometimes replace the original function with a new one, leading to loss of important function attributes like name, docstring, and argument list.
This is where functools.wraps comes into play. It is a decorator that allows users topreserve the attributes of the original function when applying a decorator. Essentially, it "wraps" the new function created by the decorator with the attributes of the original function.
Consider the following example:
def logged(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging
When you use this decorator, it ensures that the function retains its original name,docstring, and argument list, even though it has been modified by the logging functionality. Here is an example of how it works:
@logged def f(x): """does some math""" return x + x * x print(f.__name__) # prints 'f' print(f.__doc__) # prints 'does some math'
Without functools.wraps, the decorator would have replaced the original functionf with a new function with a different name and no docstring, making it difficult to identify and interpret the function's behavior.
The above is the detailed content of How Does `functools.wraps` Preserve Original Function Attributes in Python Decorators?. For more information, please follow other related articles on the PHP Chinese website!