# Prompt: Add Docstrings to Functions

Use this prompt when you need to add or improve docstrings for functions/classes.

---

## Prompt Template

```
I need to add Google-style docstrings to the following function/class:

**Code:**
```python
[Paste the function or class code here, including signature and implementation]
```

**Context:**
[Explain what this function does in the larger system]
[Mention any non-obvious behavior or edge cases]
[Note any important performance characteristics]

**Requirements:**
- Use Google-style docstring format
- Include Args section with all parameters
- Include Returns section describing return value
- Include Raises section for exceptions
- Add Examples section if function is complex
- Add Note section if there are important caveats
- Be concise but complete
- Use proper type annotations in Args section

**Target Audience:** [Developers using this function / Library users / Internal team]

Please generate the complete docstring.
```

---

## Example Usage

**Example 1: Simple Function**

```
I need to add Google-style docstrings to the following function:

**Code:**
```python
def calculate_discount(price: float, discount_percent: float) -> float:
    if discount_percent < 0 or discount_percent > 100:
        raise ValueError("Discount must be between 0 and 100")
    return price * (1 - discount_percent / 100)
```

**Context:**
This is a utility function used in the pricing module to calculate
discounted prices. It's used throughout the e-commerce system.

**Requirements:**
- Google-style docstring
- Document the validation behavior
- Simple example showing usage

**Target Audience:** Internal developers

Please generate the complete docstring.
```

**AI Response:**
```python
def calculate_discount(price: float, discount_percent: float) -> float:
    """Calculate discounted price based on original price and discount percentage.

    Args:
        price: Original price before discount (must be non-negative)
        discount_percent: Discount percentage (0-100, inclusive)

    Returns:
        Final price after applying discount

    Raises:
        ValueError: If discount_percent is not between 0 and 100

    Example:
        >>> calculate_discount(100.0, 20.0)
        80.0
        >>> calculate_discount(50.0, 10.0)
        45.0
    """
    if discount_percent < 0 or discount_percent > 100:
        raise ValueError("Discount must be between 0 and 100")
    return price * (1 - discount_percent / 100)
```

**Example 2: Complex Function**

```
I need to add Google-style docstrings to the following function:

**Code:**
```python
def process_user_data(
    user_id: str,
    data: pd.DataFrame,
    schema: Schema,
    normalize: bool = True,
    strict: bool = False
) -> tuple[ProcessedData, list[str]]:
    user = get_user(user_id)
    if not user.is_active:
        raise UserInactiveError(f"User {user_id} is inactive")

    errors = []
    if normalize:
        data = normalize_columns(data)

    try:
        validate_schema(data, schema, strict=strict)
    except SchemaValidationError as e:
        if strict:
            raise
        errors.append(str(e))

    processed = ProcessedData(
        user_id=user_id,
        data=data,
        timestamp=datetime.now()
    )

    return processed, errors
```

**Context:**
This is the main data processing function in our ETL pipeline. It validates
user data against a schema, optionally normalizes columns, and returns
processed data with any non-critical errors. In strict mode, it fails fast
on any validation errors. In non-strict mode, it collects errors but still
returns processed data.

Performance: Can process ~10k rows/second. Normalization adds ~20% overhead.
Thread-safety: Not thread-safe due to get_user() caching.

**Requirements:**
- Full Google-style docstring
- Document all parameters thoroughly
- Explain strict vs non-strict behavior
- Document exceptions
- Include examples for both modes
- Add Note about thread-safety and performance

**Target Audience:** Developers building ETL pipelines

Please generate the complete docstring.
```

**Example 3: Class**

```
I need to add Google-style docstrings to the following class:

**Code:**
```python
class DataProcessor:
    def __init__(
        self,
        schema: Schema,
        validator: Validator,
        max_workers: int = 4
    ):
        self.schema = schema
        self.validator = validator
        self.max_workers = max_workers
        self._executor = ThreadPoolExecutor(max_workers=max_workers)

    def process(self, data: pd.DataFrame) -> ProcessedData:
        # Implementation...
        pass

    def process_batch(
        self,
        batch: list[pd.DataFrame]
    ) -> list[ProcessedData]:
        # Implementation...
        pass
```

**Context:**
This class provides parallel data processing using thread pools.
It validates and processes dataframes according to a schema.
Thread pool is created on initialization and should be cleaned up
via close() method or by using as context manager.

**Requirements:**
- Add class-level docstring explaining purpose
- Add docstrings for __init__ and all methods
- Include examples showing usage as context manager
- Note about cleanup requirements

**Target Audience:** Library users

Please generate complete docstrings for the class and all methods.
```

---

## Tips for Using This Prompt

### Provide Full Context
- Include the complete function implementation
- Explain what it does in the larger system
- Mention any non-obvious behavior
- Note performance characteristics if relevant

### Specify Complexity Level
- Simple functions need brief docstrings
- Complex functions need examples and notes
- Public APIs need more detail than internal functions

### Highlight Edge Cases
- Mention validation rules
- Note error conditions
- Explain special handling

### Request Specific Sections
- Always: Args, Returns
- When applicable: Raises, Examples, Note
- For complex functions: Detailed explanation

---

## What to Expect

The AI should generate:
- ✅ Properly formatted Google-style docstring
- ✅ Complete Args section with types and descriptions
- ✅ Clear Returns description
- ✅ All exceptions documented
- ✅ Examples that actually work
- ✅ Appropriate level of detail

Review and edit:
- Verify examples are correct
- Add any missing edge cases
- Ensure technical accuracy
- Check tone matches your codebase

---

## Docstring Quality Checklist

Good docstring should have:
- [ ] One-line summary (imperative mood)
- [ ] All parameters documented with types
- [ ] Return value clearly described
- [ ] All exceptions listed with conditions
- [ ] Examples for complex functions
- [ ] Notes for important caveats
- [ ] Concise but complete

---

## Related Prompts

- [Update README](update-readme.md)
- [Update API Documentation](update-api-docs.md)
- [Write Code Comments](write-code-comments.md)

---

**Status**: Prompt template for adding docstrings. Updated: 2026-01-07
