What is Python's decorator advanced patterns?
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.
Previous
What is Python's type system and static typing with mypy?
Next
What is Python's async generators and async context managers?