🐍 Python Advanced

What is Python's decorator advanced patterns?

Why Interviewers Ask This

Senior Python engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

Answer

Advanced decorator patterns expand on the basic wrapper concept. Decorator with arguments requires an extra nesting level: def retry(times=3): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for i in range(times): try: return func(*args, **kwargs); except Exception: if i == times-1: raise; return wrapper; return decorator. Apply: @retry(times=5) def unreliable_call(). Class-based decorator: implement __init__ (stores args) and __call__ (wraps the function). Stacking decorators: @log @timer @validate def func() — applied bottom to top. Decorator for classes: accepts a class and returns a modified class. Real-world patterns: @app.route("/path") (Flask), @cache, @retry, @authenticate, @validate_schema. The functools.wraps decorator preserves the wrapped function's name, docstring, and attributes — always use it.

Pro Tip

This topic has Python-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.