---
name: python
description: Python development best practices, testing with pytest, packaging, and common patterns. Use when writing or reviewing Python code.
---

# Python Development Skill

## Code Style
- Follow PEP 8 conventions
- Use type hints for all function signatures
- Use dataclasses or Pydantic models for data containers
- Prefer f-strings over .format() or % formatting
- Use pathlib.Path instead of os.path

## Project Structure
```
project/
├── src/package_name/
│   ├── __init__.py
│   ├── main.py
│   └── utils.py
├── tests/
│   ├── __init__.py
│   ├── test_main.py
│   └── conftest.py
├── pyproject.toml
└── README.md
```

## Testing with pytest
```python
# test_example.py
import pytest

def test_basic():
    assert func(1, 2) == 3

@pytest.fixture
def sample_data():
    return {"key": "value"}

def test_with_fixture(sample_data):
    assert sample_data["key"] == "value"

@pytest.mark.parametrize("input,expected", [
    (1, 2), (2, 4), (3, 6),
])
def test_parametrized(input, expected):
    assert double(input) == expected
```

Run tests: `python -m pytest tests/ -v`

## Error Handling
```python
# Use specific exceptions
class AppError(Exception): pass
class NotFoundError(AppError): pass

# Context managers for cleanup
from contextlib import contextmanager

@contextmanager
def managed_resource():
    resource = acquire()
    try:
        yield resource
    finally:
        resource.release()
```

## Virtual Environments
```bash
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
.venv\Scripts\activate     # Windows
pip install -e ".[dev]"
```
