Decorators
As a Tech Lead engineer, explain Decorators. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Quick interview answer
At Tech Lead depth: start with the problem, then mechanism, then a short example. Decorators wrap functions: @decorator applies decorator(func).
Detailed answer
At Tech Lead depth: start with the problem, then mechanism, then a short example. Decorators wrap functions: @decorator applies decorator(func). functools.wraps preserves __name__/__doc__. Common for logging, auth, caching, retries. Core: Decorators wrap functions: @decorator applies decorator(func). functools.wraps preserves __name__/__doc__. Common for logging, auth, caching, retries. Real-time example: Flask @app.route('/users') registers URL rule; @login_required guards view functions. Pros: DRY cross-cutting logic; composable with stacking decorators. Cons: Stack order matters; debugging wrapped call stacks is harder. Common mistakes: Forgetting @wraps; decorator not returning wrapper function. Best practices: Use wraps; accept *args/**kwargs in generic decorators; prefer parameterized factory pattern. Audience level: Tech Lead.
Full explanation
Decorators wrap functions: @decorator applies decorator(func). functools.wraps preserves __name__/__doc__. Common for logging, auth, caching, retries.
Real example & use case
Flask @app.route('/users') registers URL rule; @login_required guards view functions.
Pros & cons
Pros: DRY cross-cutting logic; composable with stacking decorators. Cons: Stack order matters; debugging wrapped call stacks is harder.
Common mistakes
Forgetting @wraps; decorator not returning wrapper function.
Best practices
Use wraps; accept *args/**kwargs in generic decorators; prefer parameterized factory pattern.
Follow-up questions
Open one as its own read / solve / listen card