Skip to the solution
MediumDSA13 min read

What are decorators in Python?

1.0k views

The problem

Question presented to candidate: "You see @something above function definitions all over Python code. What is a decorator, what does the @ line actually do, and can you write one for me, say one that logs or changes what a function returns?"

What a strong answer should cover:

  • A decorator is a callable that takes a function (or class) and returns a replacement; @deco above def f means f = deco(f), applied once when the def statement runs.
  • It works because functions are first-class objects and the inner wrapper is a closure that remembers the original function.
  • The standard shape: an inner wrapper(*args, **kwargs) that calls the original, returns its result, and is decorated with functools.wraps.
  • Stacking order: the decorator nearest the def is applied first, the top one wraps everything (so it runs first at call time).
  • Real uses: logging, timing, caching (functools.lru_cache), access checks, retries, registration (web routes, plugins), property / classmethod / staticmethod, and class decorators such as dataclasses.dataclass.
  • A version fact: function decorators came with PEP 318 (Python 2.4), class decorators with PEP 3129, and PEP 614 (Python 3.9) allows any expression after @.

Code / implementation expected: Yes β€” write a small decorator (logging, timing or a result transform) live, with *args, **kwargs and functools.wraps.

  • decorators

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

13 min read Β· 13 sections

Run the code

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

PythonThe @ sugar, decoration time, stacking order and a registration decorator
PythonA class as a decorator, a class decorator, PEP 614 and the closure cell

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 53 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

How do generator pipelines stream data lazily?

Continue