# Library Module Template

## Basic Module Structure
```python
"""Module description in one line.

This module provides [functionality]. It includes:
- Feature 1
- Feature 2
- Feature 3

Example:
    Basic usage:
    >>> from mylib.module import MyClass
    >>> obj = MyClass()
    >>> result = obj.process(data)
"""

import logging
from typing import Any, Optional, Union
from dataclasses import dataclass

from .exceptions import ValidationError, ProcessingError
from .protocols import DataProcessor

__all__ = ["MyClass", "process_data", "ModuleConfig"]

logger = logging.getLogger(__name__)


@dataclass
class ModuleConfig:
    """Configuration for this module."""
    timeout: int = 30
    retries: int = 3
    strict: bool = False


class MyClass:
    """Main class with clear purpose.

    This class handles [specific responsibility]. It provides:
    - Method 1: Does X
    - Method 2: Does Y
    - Method 3: Does Z

    Attributes:
        config: Module configuration
        _state: Internal state (private)

    Example:
        >>> obj = MyClass(config=ModuleConfig(timeout=60))
        >>> result = obj.process({"key": "value"})
    """

    def __init__(self, config: Optional[ModuleConfig] = None):
        """Initialize with optional configuration.

        Args:
            config: Configuration object. Uses defaults if None.
        """
        self.config = config or ModuleConfig()
        self._state = {}
        logger.debug(f"Initialized {self.__class__.__name__} with config: {self.config}")

    def process(self, data: dict[str, Any]) -> dict[str, Any]:
        """Process data according to configuration.

        Args:
            data: Input data dictionary

        Returns:
            Processed data dictionary

        Raises:
            ValidationError: If data is invalid
            ProcessingError: If processing fails

        Example:
            >>> obj.process({"value": 100})
            {"value": 100, "processed": True}
        """
        self._validate(data)

        try:
            result = self._transform(data)
            logger.info(f"Successfully processed {len(data)} items")
            return result
        except Exception as e:
            logger.error(f"Processing failed: {e}")
            raise ProcessingError(f"Failed to process data: {e}") from e

    def _validate(self, data: dict[str, Any]) -> None:
        """Validate input data (private method).

        Args:
            data: Data to validate

        Raises:
            ValidationError: If validation fails
        """
        if not isinstance(data, dict):
            raise ValidationError(f"Expected dict, got {type(data).__name__}")

        required_fields = ["value"]
        missing = [f for f in required_fields if f not in data]
        if missing:
            raise ValidationError(f"Missing required fields: {missing}")

    def _transform(self, data: dict[str, Any]) -> dict[str, Any]:
        """Transform data (private method)."""
        return {
            **data,
            "processed": True,
            "processor": self.__class__.__name__
        }


def process_data(
    data: Union[dict, list[dict]],
    config: Optional[ModuleConfig] = None
) -> Union[dict, list[dict]]:
    """Convenience function for processing data.

    Args:
        data: Single dict or list of dicts to process
        config: Optional configuration

    Returns:
        Processed data in same format as input

    Example:
        >>> process_data({"value": 100})
        {"value": 100, "processed": True}

        >>> process_data([{"value": 100}, {"value": 200}])
        [{"value": 100, "processed": True}, {"value": 200, "processed": True}]
    """
    processor = MyClass(config)

    if isinstance(data, list):
        return [processor.process(item) for item in data]
    else:
        return processor.process(data)


# Module initialization code
def _initialize_module():
    """Initialize module (called on import)."""
    logger.debug(f"Initialized {__name__} module")

_initialize_module()
```

## Module Best Practices

### Imports Organization
```python
# Standard library
import os
import sys
from pathlib import Path

# Third-party
import requests
import numpy as np

# Local application
from .config import Config
from .exceptions import AppError
from .utils import helper_function
```

### Module-Level Documentation
```python
"""
mylib.processing
~~~~~~~~~~~~~~~~

This module provides data processing functionality.

Basic usage:
    >>> from mylib.processing import Processor
    >>> p = Processor()
    >>> result = p.process(data)

Available classes:
    - Processor: Main processing class
    - BatchProcessor: For batch operations

Available functions:
    - process_file: Process a single file
    - process_directory: Process all files in directory

For more examples see: https://docs.example.com
"""
```

### Type Hints
```python
from typing import TypeVar, Generic, Protocol

T = TypeVar('T')

class Container(Generic[T]):
    """Generic container class."""
    def __init__(self, items: list[T]):
        self._items = items

    def get(self, index: int) -> T:
        return self._items[index]
```
