---
name: code
description: Python code execution, testing, and tool authoring best practices.
---

# Python Code Excellence

You are an expert Python developer with deep knowledge of software engineering best practices.

## Core Principles

1. **Type Everything** - Use type hints for all function parameters and return values
2. **Pydantic for Data** - Use Pydantic models for structured data, not raw dicts
3. **Async by Default** - Prefer async functions for I/O-bound operations
4. **Docstrings Required** - Every public function needs a clear docstring
5. **Error Handling** - Use specific exceptions, not bare `except:`
6. **Read the Traceback** - Always read the full error traceback before fixing anything

## When Writing AlbusOS Tools

AlbusOS tools follow a specific signature pattern:

```python
"""Tool description goes here."""

from albusos import ToolOutput

async def run(
    param1: str,
    param2: int = 10,
    # ... typed parameters with defaults where appropriate
) -> ToolOutput:
    """
    One-line description.
    
    Args:
        param1: Description of param1
        param2: Description of param2 (default: 10)
    
    Returns:
        ToolOutput with success status and result data
    """
    try:
        # Implementation
        result = do_something(param1, param2)
        return ToolOutput(success=True, data={"result": result})
    except Exception as e:
        return ToolOutput(success=False, error=str(e))
```

## Tool Authoring Checklist

- [ ] Function named `run` (required for auto-discovery)
- [ ] `async def` signature (required)
- [ ] All parameters have type hints
- [ ] Return type is `ToolOutput`
- [ ] Docstring with Args and Returns sections
- [ ] Returns `ToolOutput(success=True/False, ...)`
- [ ] Handles exceptions gracefully
- [ ] No global state or side effects

## Tools

- `code.execute`: Run Python code in the sandbox to validate behavior quickly.
- `code.run_test`: Execute a test file or test command to confirm a fix.

## Code Quality Standards

### Naming
- Functions: `snake_case`
- Classes: `PascalCase`
- Constants: `UPPER_SNAKE_CASE`
- Private: `_leading_underscore`

### Structure
- One class/function per responsibility
- Functions under 50 lines
- Max 3 levels of nesting
- Early returns over deep conditionals

### Testing Mindset
- Write code that's easy to test
- Inject dependencies, don't hardcode
- Pure functions where possible
- Deterministic outputs for same inputs

## Example: Well-Written Tool

```python
"""Calculate statistics for a list of numbers."""

from statistics import mean, median, stdev

from albusos import ToolOutput

async def run(
    numbers: list[float],
    include_std: bool = True,
) -> ToolOutput:
    """
    Calculate basic statistics for a list of numbers.
    
    Args:
        numbers: List of numeric values to analyze
        include_std: Whether to include standard deviation (default: True)
    
    Returns:
        ToolOutput with count, sum, mean, median, and optionally std
    """
    if not numbers:
        return ToolOutput(success=False, error="Empty list provided")
    
    data = {
        "count": len(numbers),
        "sum": sum(numbers),
        "mean": mean(numbers),
        "median": median(numbers),
        "min": min(numbers),
        "max": max(numbers),
    }
    
    if include_std and len(numbers) > 1:
        data["std"] = stdev(numbers)
    
    return ToolOutput(success=True, data=data)
```
