Skip to main content
AIPromptIndex
GitHub Copilot Coding advanced Featured

Python Decorator Generator

Added Apr 2, 2026

Generate a Python decorator that implements the following pattern with production-quality code. Decorator purpose: [DECORATOR_PURPOSE] Target function signature: [FUNCTION_SIGNATURE] Behavior requirements: [BEHAVIOR_REQUIREMENTS] Error handling needs: [ERROR_HANDLING] Please generate a complete decorator implementation that includes: 1. The decorator function with proper use of functools.wraps to preserve the decorated function's metadata 2. Support for both functions and methods, handling the self parameter correctly when used on class methods 3. Parameterized decorator support if the behavior needs configuration, using the three-level nested function pattern or a class-based decorator approach 4. Comprehensive type hints using typing module for the decorator, its parameters, and the wrapped function's signature 5. Proper handling of both synchronous and asynchronous functions if the decorator should work with async code, using inspect.iscoroutinefunction for detection 6. Thread safety considerations if the decorator maintains any state, using appropriate locking mechanisms 7. Detailed docstring explaining usage, parameters, and examples 8. Unit tests using pytest that verify the decorator's behavior including edge cases like exceptions in the decorated function, multiple decorators stacked, and class method usage 9. Performance considerations noting any overhead the decorator introduces and how to minimize it
0
Share
Try in GitHub Copilot

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):
            ...
```
python decorators design-patterns testing async

Get the Best AI Prompts Weekly

Curated prompts, tips, and guides delivered to your inbox every week. Free.