Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

Why does a well-written decorator use `functools.wraps`, and what breaks if you skip it?

Answer

Without `functools.wraps`, a decorator's wrapper function replaces the original function entirely, including its `__name__`, `__doc__`, `__module__` and `__wrapped__` metadata, so `help(decorated_func)`, introspection tools, and anything relying on `func.__name__` (like some test frameworks and debuggers) see the generic wrapper instead of the real function. `@functools.wraps(func)` applied to the wrapper copies that metadata across automatically, and also sets `__wrapped__` to the original function, preserving the illusion that the decorated function is still recognizably itself.

Strong answer includes

  • without wraps, __name__/__doc__/__module__ get replaced by the wrapper's
  • breaks introspection tools and anything reading func.__name__
  • functools.wraps copies metadata and sets __wrapped__

Practical example

Without

Python example
@functools.wraps(func)

inside a `@log_calls` decorator, `decorated_greet.__name__` reports `"wrapper"` instead of `"greet"` , breaking auto-generated API documentation that lists function names.

#decorators#functools

Sources

functools — Higher-order functions and operations on callable objectsPython Software Foundation · lru_cache, partial, wraps, reduce and singledispatch behavior