Python Developer interview question

How do Python decorators work?

A decorator receives a function or class and returns a replacement, usually a wrapper that adds behaviour; functools.wraps preserves metadata and the wrapper must keep the original contract.

Direct answer

What a strong answer covers

How it works

A decorator is ordinary function application: @deco above def f is the same as f = deco(f), evaluated once at definition time. Most decorators return a wrapper closure that runs before and after the original, forwarding *args and **kwargs and the return value. functools.wraps copies the name, docstring, and signature metadata so introspection and tooling keep working. Decorators with parameters are functions that return a decorator, which is why they have three nested levels.

Example

A retry decorator wraps a call in a loop that catches a configured exception type, sleeps with backoff, and re-raises after the last attempt; applying it as @retry(times=3, exceptions=(TimeoutError,)) keeps the business function readable. Because the wrapper runs at call time, the decorator can also be used to time or cache the function without editing its body.

Common mistakes

  • Forgetting functools.wraps so the decorated function reports the wrapper’s name in logs and docs.
  • Doing work at decoration time that was meant to happen per call.
  • Writing a wrapper that drops the return value or swallows exceptions from the original.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Python Developer interview questions