Python Development Rules
Overview
Python development guidance focused on code quality, error handling, testing, and environment management. Apply when working with Python code or Jupyter notebooks.
When to Use This Skill
Use this skill when:
- Writing new Python code or modifying existing Python files
- Creating or updating Jupyter notebooks
- Setting up Python development environments
- Writing or updating tests
- Reviewing Python code for quality and best practices
Code Quality
Principles
- DRY (Don't Repeat Yourself): Avoid code duplication
- Composition over inheritance: Prefer composition patterns
- Pure functions when possible: Functions without side effects
- Simple solutions over clever ones: Prioritize readability and maintainability
- Design for common use cases first: Solve the primary problem before edge cases
Style & Documentation
- Type hints required: All functions must include type annotations
- snake_case naming: Use snake_case for variables, functions, and modules
- Google-style docstrings: Document functions, classes, and modules using Google-style docstrings
- Keep functions small: Single responsibility principle - one function, one purpose
- Preserve existing comments: Maintain and update existing code comments
Example
def calculate_total(items: list[dict[str, float]], tax_rate: float = 0.08) -> float:
"""Calculate total cost including tax.
Args:
items: List of items with 'price' key
tax_rate: Tax rate as decimal (default 0.08)
Returns:
Total cost including tax
Raises:
ValueError: If tax_rate is negative or items list is empty
"""
if not items:
raise ValueError("Items list cannot be empty")
if tax_rate < 0:
raise ValueError("Tax rate cannot be negative")
subtotal = sum(item['price'] for item in items)
return subtotal * (1 + tax_rate)
Error Handling & Efficiency
Error Handling
- Specific exception types: Catch specific exceptions, not bare
except
- Validate inputs early: Check inputs at function entry
- No bare except: Always specify exception types
Efficiency Patterns
- f-strings: Use f-strings for string formatting
- Comprehensions: Prefer list/dict/set comprehensions over loops when appropriate
- Context managers: Use
with statements for resource management
Example
def process_file(file_path: str) -> list[str]:
"""Process file and return lines.
Args:
file_path: Path to file
Returns:
List of non-empty lines
Raises:
FileNotFoundError: If file doesn't exist
PermissionError: If file cannot be read
"""
if not file_path:
raise ValueError("File path cannot be empty")
try:
with open(file_path, 'r', encoding='utf-8') as f:
return [line.strip() for line in f if line.strip()]
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {file_path}")
except PermissionError:
raise PermissionError(f"Permission denied: {file_path}")
Testing (Critical)
Framework & Structure
- pytest only: Use pytest exclusively (no unittest)
- Test location: All tests in
./tests/ directory
- Test package: Include
__init__.py in tests directory
- TDD approach: Write/update tests for all new/modified code
- All tests must pass: Ensure all tests pass before task completion
Test Structure Example
project/
├── src/
│ └── my_module.py
└── tests/
├── __init__.py
└── test_my_module.py
Example Test
# tests/test_calculations.py
import pytest
from src.calculations import calculate_total
def test_calculate_total_basic():
"""Test basic total calculation."""
items = [{'price': 10.0}, {'price': 20.0}]
result = calculate_total(items, tax_rate=0.1)
assert result == 33.0
def test_calculate_total_empty_list():
"""Test error handling for empty list."""
with pytest.raises(ValueError, match="Items list cannot be empty"):
calculate_total([])
def test_calculate_total_negative_tax():
"""Test error handling for negative tax rate."""
items = [{'price': 10.0}]
with pytest.raises(ValueError, match="Tax rate cannot be negative"):
calculate_total(items, tax_rate=-0.1)
Environment Management
Dependency Management
- Use uv exclusively: All packaging, environment, and script execution via uv
- No pip/venv/conda: Do not use
pip, python3 -m venv, or conda — uv handles all of this
- pyproject.toml is the source of truth: Define all dependencies in
pyproject.toml (not requirements.txt)
Environment Setup Example
# Install dependencies from pyproject.toml
uv sync
# Install with optional dev dependencies
uv sync --extra dev
# Run a script (no activation needed)
uv run python script.py
# Run pytest
uv run pytest
# Add a new dependency
uv add requests
# Remove a dependency
uv remove requests
Running Python Code
- Use
uv run to execute scripts — no manual venv activation needed
- Use
uv run <tool> for dev tools (pytest, ruff, etc.)
- Dependencies are defined in
pyproject.toml (not requirements.txt)
Linting & Formatting (Ruff)
- Ruff: Use Ruff for linting AND formatting (replaces flake8, black, isort)
# Lint code
uv run ruff check .
# Lint and auto-fix
uv run ruff check --fix .
# Format code
uv run ruff format .
# Check formatting without changes
uv run ruff format --check .
Type Checking (Pyright)
# Check types
uv run pyright
Note: Use pyright for type checking — do not use mypy.
Best Practices Summary
- Code Quality: DRY, composition, pure functions, simple solutions
- Style: Type hints, snake_case, Google docstrings, small functions
- Errors: Specific exceptions, early validation, no bare except
- Efficiency: f-strings, comprehensions, context managers
- Testing: pytest only, TDD, tests in
./tests/, all must pass
- Environment: Use
uv exclusively for dependencies and execution, Ruff for linting/formatting, Pyright for type checking
1---2name: python-dev3description: Python development guidance with code quality standards, error handling, testing practices, and environment management. Use when writing, reviewing, or modifying Python code (.py files) or Jupyter notebooks (.ipynb files).4---56# Python Development Rules78## Overview9Python development guidance focused on code quality, error handling, testing, and environment management. Apply when working with Python code or Jupyter notebooks.1011## When to Use This Skill1213Use this skill when:14- Writing new Python code or modifying existing Python files15- Creating or updating Jupyter notebooks16- Setting up Python development environments17- Writing or updating tests18- Reviewing Python code for quality and best practices1920## Code Quality2122### Principles23- **DRY (Don't Repeat Yourself)**: Avoid code duplication24- **Composition over inheritance**: Prefer composition patterns25- **Pure functions when possible**: Functions without side effects26- **Simple solutions over clever ones**: Prioritize readability and maintainability27- **Design for common use cases first**: Solve the primary problem before edge cases2829### Style & Documentation30- **Type hints required**: All functions must include type annotations31- **snake_case naming**: Use snake_case for variables, functions, and modules32- **Google-style docstrings**: Document functions, classes, and modules using Google-style docstrings33- **Keep functions small**: Single responsibility principle - one function, one purpose34- **Preserve existing comments**: Maintain and update existing code comments3536### Example3738```python39def calculate_total(items: list[dict[str, float]], tax_rate: float = 0.08) -> float:40 """Calculate total cost including tax.41 42 Args:43 items: List of items with 'price' key44 tax_rate: Tax rate as decimal (default 0.08)45 46 Returns:47 Total cost including tax48 49 Raises:50 ValueError: If tax_rate is negative or items list is empty51 """52 if not items:53 raise ValueError("Items list cannot be empty")54 if tax_rate < 0:55 raise ValueError("Tax rate cannot be negative")56 57 subtotal = sum(item['price'] for item in items)58 return subtotal * (1 + tax_rate)59```6061## Error Handling & Efficiency6263### Error Handling64- **Specific exception types**: Catch specific exceptions, not bare `except`65- **Validate inputs early**: Check inputs at function entry66- **No bare except**: Always specify exception types6768### Efficiency Patterns69- **f-strings**: Use f-strings for string formatting70- **Comprehensions**: Prefer list/dict/set comprehensions over loops when appropriate71- **Context managers**: Use `with` statements for resource management7273### Example7475```python76def process_file(file_path: str) -> list[str]:77 """Process file and return lines.78 79 Args:80 file_path: Path to file81 82 Returns:83 List of non-empty lines84 85 Raises:86 FileNotFoundError: If file doesn't exist87 PermissionError: If file cannot be read88 """89 if not file_path:90 raise ValueError("File path cannot be empty")91 92 try:93 with open(file_path, 'r', encoding='utf-8') as f:94 return [line.strip() for line in f if line.strip()]95 except FileNotFoundError:96 raise FileNotFoundError(f"File not found: {file_path}")97 except PermissionError:98 raise PermissionError(f"Permission denied: {file_path}")99```100101## Testing (Critical)102103### Framework & Structure104- **pytest only**: Use pytest exclusively (no unittest)105- **Test location**: All tests in `./tests/` directory106- **Test package**: Include `__init__.py` in tests directory107- **TDD approach**: Write/update tests for all new/modified code108- **All tests must pass**: Ensure all tests pass before task completion109110### Test Structure Example111112```113project/114├── src/115│ └── my_module.py116└── tests/117 ├── __init__.py118 └── test_my_module.py119```120121### Example Test122123```python124# tests/test_calculations.py125import pytest126from src.calculations import calculate_total127128def test_calculate_total_basic():129 """Test basic total calculation."""130 items = [{'price': 10.0}, {'price': 20.0}]131 result = calculate_total(items, tax_rate=0.1)132 assert result == 33.0133134def test_calculate_total_empty_list():135 """Test error handling for empty list."""136 with pytest.raises(ValueError, match="Items list cannot be empty"):137 calculate_total([])138139def test_calculate_total_negative_tax():140 """Test error handling for negative tax rate."""141 items = [{'price': 10.0}]142 with pytest.raises(ValueError, match="Tax rate cannot be negative"):143 calculate_total(items, tax_rate=-0.1)144```145146## Environment Management147148### Dependency Management149- **Use uv exclusively**: All packaging, environment, and script execution via [uv](https://github.com/astral-sh/uv)150- **No pip/venv/conda**: Do not use `pip`, `python3 -m venv`, or `conda` — `uv` handles all of this151- **pyproject.toml is the source of truth**: Define all dependencies in `pyproject.toml` (not `requirements.txt`)152153### Environment Setup Example154155```bash156# Install dependencies from pyproject.toml157uv sync158159# Install with optional dev dependencies160uv sync --extra dev161162# Run a script (no activation needed)163uv run python script.py164165# Run pytest166uv run pytest167168# Add a new dependency169uv add requests170171# Remove a dependency172uv remove requests173```174175### Running Python Code176- Use `uv run` to execute scripts — no manual venv activation needed177- Use `uv run <tool>` for dev tools (pytest, ruff, etc.)178- Dependencies are defined in `pyproject.toml` (not requirements.txt)179180### Linting & Formatting (Ruff)181- **Ruff**: Use Ruff for linting AND formatting (replaces flake8, black, isort)182183```bash184# Lint code185uv run ruff check .186187# Lint and auto-fix188uv run ruff check --fix .189190# Format code191uv run ruff format .192193# Check formatting without changes194uv run ruff format --check .195```196197### Type Checking (Pyright)198199```bash200# Check types201uv run pyright202```203204Note: Use `pyright` for type checking — do not use `mypy`.205206## Best Practices Summary2072081. **Code Quality**: DRY, composition, pure functions, simple solutions2092. **Style**: Type hints, snake_case, Google docstrings, small functions2103. **Errors**: Specific exceptions, early validation, no bare except2114. **Efficiency**: f-strings, comprehensions, context managers2125. **Testing**: pytest only, TDD, tests in `./tests/`, all must pass2136. **Environment**: Use `uv` exclusively for dependencies and execution, Ruff for linting/formatting, Pyright for type checking214