Repaso
EspaƱol
PythonIntermediatePY-07

Why use functools.wraps inside a decorator?

Options

  1. It makes the wrapper run faster by skipping one function call
  2. It copies __name__ and __doc__ from the original function (Correct option)
  3. It lets the decorator accept arguments when it is applied to code
  4. 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.

Key terms

Practice this question in Repaso