Python core · Concept
Decorators
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- What breaks if you forget
functools.wraps? - How do you write a decorator that takes arguments, like
@retry(times=3)? - In what order do two stacked decorators run?
- Your decorator works on normal functions but not on
async defones. Why?
The answer
What a strong answer covers
- Functions are objects.
@dabovedef fmeansf = d(f), run once when the function is defined. - A typical decorator returns a wrapper closure that calls the original with
*args, **kwargs. functools.wrapscopies__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 defneeds 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 voicePractise 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.