Skip to the solution
MediumDSA10 min read

Why use functools.wraps when writing decorators?

503 views

The problem

Question presented to candidate: "Most decorator examples put @functools.wraps(func) on the inner wrapper. What goes wrong if you leave it out, and what exactly does wraps do?"

What a strong answer should cover:

  • Without it, the decorated name points at the wrapper, so __name__, __qualname__, __doc__, __module__ and annotations describe the wrapper, not the original.
  • What breaks: logs and tracebacks that print names, help() and docs, inspect.signature, registries keyed by __name__, and pickle, which finds functions by module and qualified name.
  • What wraps does: it is functools.update_wrapper as a decorator; it copies WRAPPER_ASSIGNMENTS, merges WRAPPER_UPDATES (__dict__) and sets __wrapped__ to the original.
  • __wrapped__ lets inspect.signature report the real signature and lets inspect.unwrap or tests reach the undecorated function.
  • What it does not do: it does not change the wrapper code, defaults or behaviour; it only copies metadata. A version detail: 3.12 added __type_params__ to the copied attributes.

Code / implementation expected: Yes β€” a decorator with and without wraps, printing __name__, __doc__ and the signature.

  • decorator
  • wraps

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonMetadata, signature and __wrapped__ with and without functools.wraps
PythonReal bugs: a name-keyed registry, pickling, and reaching the original

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 84 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What are generators and why use them?

Continue