Python Decorator Generator
Added Apr 2, 2026
About This Prompt
This prompt generates production-ready Python decorators that follow best practices for metadata preservation, type safety, and async compatibility. It goes beyond simple examples by handling real-world concerns like thread safety for stateful decorators, class method support, and parameterized configuration. The output includes comprehensive type hints and pytest test suites, making the decorators ready to integrate into professional codebases. It is ideal for Python developers who need common patterns like retry logic, caching, rate limiting, logging, or authentication checks implemented as clean, reusable decorators. The included tests and documentation make it suitable for shared libraries and team codebases where code quality standards matter.
Variables to Customize
[DECORATOR_PURPOSE]
What the decorator should do
Example: Retry a function up to N times with exponential backoff when specific exceptions are raised
[FUNCTION_SIGNATURE]
The typical function this decorator will wrap
Example: async def fetch_data(url: str, timeout: int = 30) -> dict
[BEHAVIOR_REQUIREMENTS]
Specific behavioral details for the decorator
Example: Configurable max retries (default 3), exponential backoff starting at 1 second, jitter of 0-500ms, only retry on ConnectionError and TimeoutError, log each retry attempt
[ERROR_HANDLING]
How the decorator should handle failures
Example: After max retries exhausted, raise the last exception with a RetryExhausted wrapper that includes attempt count and total elapsed time
Tips for Best Results
- Specify whether the decorator needs to work with async functions since this significantly changes the implementation
- Mention if the decorator will be stacked with other decorators so the implementation handles composition correctly
- Include the Python version you are targeting since features like ParamSpec (3.10+) enable better type hints for decorators
Example Output
```python
import functools
import asyncio
import random
import time
import logging
from typing import TypeVar, Callable, Type
logger = logging.getLogger(__name__)
class RetryExhausted(Exception):
def __init__(self, attempts: int, elapsed: float, last_exception: Exception):
self.attempts = attempts
self.elapsed = elapsed
super().__init__(f"Retry exhausted after {attempts} attempts ({elapsed:.2f}s): {last_exception}")
def retry(
max_attempts: int = 3,
backoff_base: float = 1.0,
jitter_max: float = 0.5,
retry_on: tuple[Type[Exception], ...] = (ConnectionError, TimeoutError),
):
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
async def async_wrapper(*args, **kwargs):
...
```