Why use functools.wraps inside a decorator?
Options
- It makes the wrapper run faster by skipping one function call
- It copies
__name__and__doc__from the original function (Correct option) - It lets the decorator accept arguments when it is applied to code
- It caches the result of the function between two calls
Answer
It copies metadata (__name__, __doc__, __wrapped__) from the original function onto the wrapper
Why
A decorator replaces your function with a new one (the wrapper). Without @wraps, the result looks like the wrapper: its name becomes 'wrapper' and your docstring disappears.
That confuses logs, debuggers, documentation tools and frameworks that use the function name.
@functools.wraps(func) copies the name, docstring and other metadata from the original function to the wrapper.
Remember
Always put @functools.wraps(func) on the inner wrapper.