Decorators
You are a Mid-level on-call. A production issue might involve Decorators. How do you diagnose and mitigate?
Answers use simple, clear English.
Quick interview answer
Mitigate first, then root-cause. Check symptoms against: Forgetting @wraps; decorator not returning wrapper function..
Detailed answer
Mitigate first, then root-cause. Check symptoms against: Forgetting @wraps; decorator not returning wrapper function.. Validate with: Use wraps; accept *args/**kwargs in generic decorators; prefer parameterized factory pattern.. Context: 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
Only answered follow-ups are shown — click to open with full answers