AI assistant for Python development with emphasis on clean architecture, type safety, testing with pytest, and modern tooling (uv, Ruff). Enforces comprehensive docstrings, type annotations, and structured project organization.
A comprehensive Python development skill focused on clean code, type safety, robust testing, and modern tooling.
This skill guides AI assistants to write production-quality Python code following industry best practices. It emphasizes clear project structure, comprehensive type annotations, pytest-based testing, detailed documentation, and modern Python tooling.
When assisting with Python development, follow these principles and rules:
1. **Organize projects with clear separation of concerns:**
- `src/` for source code
- `tests/` for test files
- `docs/` for documentation
- Configuration files at root level
2. **Use modular design:**
- Separate files for models, services, controllers, and utilities
- Keep files focused and cohesive
- Create `__init__.py` files in all package directories
3. **Type Annotations (MANDATORY):**
- Add typing annotations to EVERY function and class
- Include return types for all functions
- Use modern type hints (from `typing` module or Python 3.10+ syntax)
- Example:
```python
def process_data(input_data: list[str], max_items: int = 10) -> dict[str, Any]:
"""Process the input data and return results."""
...
```
4. **Documentation (MANDATORY):**
- Write descriptive docstrings for ALL functions and classes
- Follow PEP 257 convention
- Update existing docstrings when modifying code
- Include parameter descriptions, return values, and exceptions raised
- Example:
```python
def calculate_total(items: list[float], tax_rate: float) -> float:
"""Calculate the total cost including tax.
Args:
items: List of item prices
tax_rate: Tax rate as decimal (e.g., 0.08 for 8%)
Returns:
Total cost including tax
Raises:
ValueError: If tax_rate is negative
"""
...
```
5. **Preserve existing code:**
- Keep ALL existing comments when modifying files
- Maintain code style consistency with existing codebase
6. **Use pytest exclusively:**
- DO NOT use the `unittest` module
- Use pytest or pytest plugins only
- Place all tests in `./tests` directory
- Create necessary folders and `__init__.py` files
7. **Test file requirements:**
- ALL tests must have typing annotations
- ALL tests must include docstrings
- When using pytest fixtures, import types for type checking:
```python
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from _pytest.capture import CaptureFixture
from _pytest.fixtures import FixtureRequest
from _pytest.logging import LogCaptureFixture
from _pytest.monkeypatch import MonkeyPatch
from pytest_mock.plugin import MockerFixture
```
8. **Test structure example:**
```python
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pytest_mock.plugin import MockerFixture
def test_user_creation(mocker: "MockerFixture") -> None:
"""Test that user creation works correctly with valid data."""
mock_db = mocker.patch("app.database.save_user")
# ... test implementation
```
9. **Configuration management:**
- Use environment variables for configuration
- Never hardcode sensitive data
- Use `.env` files with `python-dotenv` or similar
10. **Error handling and logging:**
- Implement robust error handling with context capture
- Use Python's `logging` module
- Log errors with sufficient context for debugging
11. **Dependency management:**
- Use [uv](https://github.com/astral-sh/uv) for fast dependency management
- Maintain `pyproject.toml` or `requirements.txt`
- Use virtual environments
12. **Code style:**
- Use Ruff for linting and formatting
- Maintain consistency across the codebase
- Follow PEP 8 guidelines
13. **CI/CD:**
- Implement continuous integration with GitHub Actions or GitLab CI
- Run tests, linting, and type checking in CI pipeline
```python
from typing import Optional
def fetch_user_data(user_id: int, include_deleted: bool = False) -> Optional[dict[str, Any]]:
"""Fetch user data from the database.
Args:
user_id: The unique identifier for the user
include_deleted: Whether to include soft-deleted users
Returns:
User data dictionary if found, None otherwise
Raises:
DatabaseError: If database connection fails
"""
...
```
```python
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from pytest_mock.plugin import MockerFixture
def test_calculate_discount(mocker: "MockerFixture") -> None:
"""Test discount calculation with various input scenarios."""
result = calculate_discount(100.0, 0.2)
assert result == 80.0
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/python-development-best-practices-w3nsd2/raw