Decorators
As a Mid-level 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 Mid-level depth: start with the problem, then mechanism, then a short example. Decorators wrap functions: @decorator applies decorator(func).
Detailed answer
At Mid-level 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: Mid-level.
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