Get the FREE Ultimate OpenClaw Setup Guide →

python-standards

Scanned
npx machina-cli add skill akaszubski/autonomous-dev/python-standards --openclaw
Files (1)
SKILL.md
5.2 KB

Python Standards Skill

Python code quality standards for autonomous-dev project.

When This Activates

  • Writing Python code
  • Code formatting
  • Type hints
  • Docstrings
  • Keywords: "python", "format", "type", "docstring"

Code Style (PEP 8 + Black)

SettingValue
Line length100 characters
Indentation4 spaces (no tabs)
QuotesDouble quotes
ImportsSorted with isort
black --line-length=100 src/ tests/
isort --profile=black --line-length=100 src/ tests/

Type Hints (Required)

Rule: All public functions must have type hints on parameters and return.

def process_file(
    input_path: Path,
    output_path: Optional[Path] = None,
    *,
    max_lines: int = 1000
) -> Dict[str, any]:
    """Type hints on all parameters and return."""
    pass

Docstrings (Google Style)

Rule: All public functions/classes need docstrings with Args, Returns, Raises.

def process_data(data: List[Dict], *, batch_size: int = 32) -> ProcessResult:
    """Process data with validation.

    Args:
        data: Input data as list of dicts
        batch_size: Items per batch (default: 32)

    Returns:
        ProcessResult with items and metrics

    Raises:
        ValueError: If data is empty
    """

Error Handling

Rule: Error messages must include context + expected + docs link.

# ✅ GOOD
raise FileNotFoundError(
    f"Config file not found: {path}\n"
    f"Expected: YAML with keys: model, data\n"
    f"See: docs/guides/configuration.md"
)

# ❌ BAD
raise FileNotFoundError("File not found")

Exception Hierarchy

Define a project-level exception hierarchy for structured error handling:

class AppError(Exception):
    """Base exception for the application."""
    pass

class ConfigError(AppError):
    """Configuration loading or validation error."""
    pass

class ValidationError(AppError):
    """Input or data validation error."""
    pass

class ExternalServiceError(AppError):
    """Error communicating with external service."""
    pass

When to use custom vs built-in exceptions:

  • Use built-in (ValueError, TypeError, FileNotFoundError) for standard programming errors
  • Use custom exceptions when callers need to catch specific application-level failures
  • Always inherit from a project base exception for catch-all handling

Error Message Format

Every error message should follow this three-part format:

  1. Context - What happened and where
  2. Expected - What was expected instead
  3. Docs link - Where to find more information
raise ValidationError(
    f"Invalid config key '{key}' in {config_path}\n"
    f"Expected one of: {', '.join(valid_keys)}\n"
    f"See: docs/configuration.md#valid-keys"
)

Graceful Degradation

When a non-critical operation fails, log and continue rather than crashing:

try:
    optional_result = enhance_with_cache(data)
except CacheError:
    logging.warning("Cache unavailable, proceeding without cache")
    optional_result = None

Naming Conventions

TypeConventionExample
ClassesPascalCaseModelTrainer
Functionssnake_casetrain_model()
ConstantsUPPER_SNAKEMAX_LENGTH
Private_underscore_helper()

Best Practices

  1. Keyword-only args - Use * for clarity
  2. Pathlib - Use Path not string paths
  3. Context managers - Use with for resources
  4. Dataclasses - For configuration objects
# Keyword-only args
def train(data: List, *, learning_rate: float = 1e-4):
    pass

# Pathlib
config = Path("config.yaml").read_text()

Code Quality Commands

flake8 src/ --max-line-length=100       # Linting
mypy src/[project_name]/                # Type checking
pytest --cov=src --cov-fail-under=80    # Coverage

Key Takeaways

  1. Type hints - Required on all public functions
  2. Docstrings - Google style, with Args/Returns/Raises
  3. Black formatting - 100 char line length
  4. isort imports - Sorted and organized
  5. Helpful errors - Context + expected + docs link
  6. Pathlib - Use Path not string paths
  7. Keyword args - Use * for clarity
  8. Dataclasses - For configuration objects

Related Skills

  • testing-guide - Testing patterns and TDD methodology
  • error-handling-patterns - Error handling best practices

Hard Rules

FORBIDDEN:

  • Public functions without type hints on parameters and return values
  • Bare except: or except Exception: without re-raising or specific handling
  • Mutable default arguments (def f(items=[]))
  • Using os.path when pathlib.Path is available

REQUIRED:

  • All public APIs MUST have Google-style docstrings with Args/Returns/Raises
  • All code MUST pass black formatting (100 char line length)
  • Imports MUST be sorted with isort (profile=black)
  • Keyword-only arguments MUST be used for functions with 2+ optional parameters

Source

git clone https://github.com/akaszubski/autonomous-dev/blob/master/plugins/autonomous-dev/skills/python-standards/SKILL.mdView on GitHub

Overview

Provides standards for Python code in the autonomous-dev project. It enforces PEP 8 conventions, type hints on public APIs, and Google-style docstrings. It also defines error handling, naming conventions, and practical best practices to keep code maintainable.

How This Skill Works

The skill prescribes tooling and conventions: Black for formatting, isort for import sorting, line length 100, 4-space indentation, and double quotes. It requires type hints on all public functions and Google-style docstrings. It defines an error-handling framework with a project-wide exception hierarchy and standardized error messages.

When to Use It

  • Starting a new Python module in the autonomous-dev project
  • Running code formatting and linting passes
  • Adding or updating public APIs with type hints
  • Documenting functions/classes with Google-style docstrings
  • Improving error handling with consistent context, expectation, and docs links

Quick Start

  1. Step 1: Run Black and isort with 100 line length on src/ and tests/ to enforce formatting
  2. Step 2: Add type hints to all public functions and write Google-style docstrings
  3. Step 3: Introduce the AppError hierarchy and standardize error messages with context, expected, and docs link

Best Practices

  • Keyword-only args using * for clarity
  • Pathlib usage: prefer Path over raw string paths
  • Context managers (with) for resource handling
  • Dataclasses for configuration objects
  • Define a project-wide exception hierarchy with AppError and derived classes

Example Use Cases

  • Annotate a public function with type hints for all parameters and the return type, e.g., def process_file(input_path: Path, output_path: Optional[Path] = None, *, max_lines: int = 1000) -> Dict[str, Any]
  • Add a Google-style docstring with Args, Returns, and Raises to a public function
  • Raise an error with context, expected, and docs link using a custom exception derived from AppError
  • Create an exception hierarchy: AppError, ConfigError, ValidationError, ExternalServiceError
  • Format code with Black and sort imports with isort using line-length 100

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers