Skip to the page

Python core · Concept

Decorators

The interviewer asks

What is a decorator, and what really happens when you put @something above a function? Give me a real use from your work.

Then

Follow-ups the interviewer asks next

  1. What breaks if you forget functools.wraps?
  2. How do you write a decorator that takes arguments, like @retry(times=3)?
  3. In what order do two stacked decorators run?
  4. Your decorator works on normal functions but not on async def ones. Why?

The answer

What a strong answer covers

  • Functions are objects. @d above def f means f = d(f), run once when the function is defined.
  • A typical decorator returns a wrapper closure that calls the original with *args, **kwargs.
  • functools.wraps copies __name__, __doc__ and sets __wrapped__; without it, logs, routes and registries see "wrapper".
  • With arguments: a factory that returns the decorator (three levels).
  • Stacking: applied bottom-up, so the top one runs first when called.
  • Real uses: logging, timing, retries, permission checks, caching (functools.cache), registering handlers, @property, @dataclass, @contextmanager.
  • An async def needs an async wrapper that awaits; otherwise the timing or retry wraps only the coroutine's creation.

The red pen

Common traps

Avoid:a definition with no real use; forgetting that decorator code runs at import time.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview