Phase 5 of 25 · Topic 5.3

Parametrized Decorators (3-Tier Decorator Factories)

1Concept

To pass arguments to a decorator (`@retry(max_attempts=3)`), a 3-tier function factory is required: Tier 1 accepts configuration arguments; Tier 2 accepts the target function; Tier 3 is the actual runtime wrapper.

2Architecture Diagram

@retry(max_attempts=3)  ---> Tier 1: retry(max_attempts=3)
                            Tier 2: decorator(func)
                            Tier 3: wrapper(*args, **kwargs)

3Code Example

Python 3.12
from functools import wraps

def retry(max_attempts: int):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_attempts + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print(f"Attempt {attempt} failed: {e}")
                    if attempt == max_attempts:
                        raise
        return wrapper
    return decorator

@retry(max_attempts=2)
def unreliable_api():
    raise ConnectionError("Gateway 504 Timeout")

try:
    unreliable_api()
except ConnectionError:
    print("Max retry attempts exhausted.")

4Expected Output

Attempt 1 failed: Gateway 504 Timeout
Attempt 2 failed: Gateway 504 Timeout
Max retry attempts exhausted.

5Key Takeaways

  • Parametrized decorators require 3 levels of nested functions.
  • Tier 1 returns the decorator; Tier 2 returns the wrapper.
  • Ideal for configuring rate limits, timeouts, and authorization role checks.