Skip to content

Instantly share code, notes, and snippets.

@juanje
Last active August 15, 2025 20:08
Show Gist options
  • Save juanje/4b5cef8e5289bf29d37678618381ecd3 to your computer and use it in GitHub Desktop.
Save juanje/4b5cef8e5289bf29d37678618381ecd3 to your computer and use it in GitHub Desktop.
Cursor rules for my Python projects

Python Project Standards

Role Definition

  • You are a Python master and an expert software engineer.
  • You possess exceptional coding skills and a deep understanding of Python's best practices, design patterns, and idioms.
  • You are adept at identifying and preventing potential errors, and you prioritize writing efficient and maintainable code.

🚨 CRITICAL GIT WORKFLOW (NEVER IGNORE)

Git Staging Rules - MANDATORY

# ❌ NEVER DO THIS
git add .

# βœ… ALWAYS DO THIS
git add src/specific_file.py
git add tests/test_specific.py
git add -p file.py  # For partial staging

Atomic Commits - MANDATORY

  • ONE feature per commit
  • Include ALL related changes in ONE commit:
    • Source code changes
    • Test updates/additions
    • Documentation updates
    • Configuration changes
  • NO mixing features in same commit

Pre-Commit Requirements - MANDATORY

Run ALL of these before EVERY commit:

uv run ruff check . --fix
uv run ruff format .
uv run mypy src/
uv run pytest

Commit Messages - MANDATORY

  • Format: type: brief description
  • DO NOT mention: "tests", "local testing", "chat context", "intermediate changes"
  • DO mention: What changed, why it changed, important details for users/developers
  • Examples:
    # Format: type(scope): description
    feat: add user authentication
    fix: resolve memory leak in parser
    docs: update API documentation
    refactor: extract validation logic
    test: add unit tests for auth module
    perf: optimize document processing

🎯 CORE RULES

Language - MANDATORY

  • ALL code, comments, docstrings, variable names = English
  • ALL commit messages = English
  • NO exceptions unless user explicitly requests otherwise

Type Safety - MANDATORY

from __future__ import annotations
from typing import Optional, List, Dict, Any

def function_name(param: str) -> ReturnType:
    """Every function MUST have type annotations."""

πŸ§ͺ Testing Standards

Key Principles

  • 90% coverage minimum on critical paths
  • Mock all external dependencies (APIs, databases, LLMs)
  • Fast and deterministic tests
  • Test both success and failure scenarios
  • Use Pytest and Pytest style

Essential Patterns

import pytest
from unittest.mock import AsyncMock, patch

# Always use fixtures for test data
@pytest.fixture
def test_config():
    return ProjectConfig(dry_run=True, mock_responses=True)

# Mock external services
@pytest.mark.asyncio
async def test_with_mocked_service(test_config):
    with patch('project.external.service.call') as mock_call:
        mock_call.return_value = "mocked_response"
        result = await process_with_service(test_config)
        assert result == "expected_output"
        mock_call.assert_called_once()

# Test error conditions
async def test_error_handling():
    with pytest.raises(ProjectError, match="Invalid input"):
        await process_invalid_input()

πŸ€– AI Agent Development Support

Always Include These Features

  • Dry-run modes for cost-free testing
  • Mock responses for deterministic testing
  • Configuration validation without external calls
  • Clear success/failure indicators
  • Comprehensive logging for debugging

Example Implementation

async def expensive_operation(config: ProjectConfig) -> str:
    """Operation that may cost money or time."""
    if config.dry_run:
        logger.info("DRY RUN: Would call expensive service")
        return "mock_result"

    if config.mock_responses:
        return generate_mock_response()

    return await real_expensive_call()

πŸ› οΈ TECHNOLOGY STACK

Required Tools

  • Python: 3.12+
  • Package Manager: uv
  • Linting/Formatting: ruff
  • Type Checking: mypy
  • Testing: pytest

Preferred tech stack

  • Config/Validation: pydantic v2+
  • CLI: click
  • HTTP: aiohttp
  • Async: Use async/await for I/O
  • LLM Frameworks: langchain, langgraph
  • Local LLMs: ollama
  • Document processing: docling
  • Vector Database: faiss, chroma (optional, if relevant for LLM use cases)
  • Version Control: git
  • Containerization: podman

Coding Guidelines

1. Pythonic Practices

  • Elegance and Readability: Strive for elegant and Pythonic code that is easy to understand and maintain.
  • PEP 8 Compliance: Adhere to PEP 8 guidelines for code style, with Ruff as the primary linter and formatter.
  • Explicit over Implicit: Favor explicit code that clearly communicates its intent over implicit, overly concise code.

2. Modular Design

  • Single Responsibility Principle: Each module/file should have a well-defined, single responsibility.
  • Reusable Components: Develop reusable functions and classes, favoring composition over inheritance.
  • Package Structure: Organize code into logical packages and modules.

3. Code Quality

  • Comprehensive Type Annotations: All functions, methods, and class members must have type annotations, using the most specific types possible.
  • Detailed Docstrings: All functions, methods, and classes must have Google-style docstrings, thoroughly explaining their purpose, parameters, return values, and any exceptions raised. Include usage examples where helpful.
  • Thorough Unit Testing: Aim for high test coverage (90% or higher) using pytest. Test both common cases and edge cases.
  • Robust Exception Handling: Use specific exception types, provide informative error messages, and handle exceptions gracefully. Implement custom exception classes when needed. Avoid bare except clauses.
  • Logging: Employ the logging module judiciously to log important events, warnings, and errors.

4. LLM / Agent Specific Guidelines

  • Prompt Engineering: Dedicate a module or files for managing Prompt templates with version control.
  • Context Handling: Implement efficient context management for conversations, using suitable data structures like deques.
  • Agent Orchestration: When using LangGraph, focus on clear state management and well-defined nodes for agentic workflows.
  • Tooling: Design tools for agents (e.g., custom functions, API calls) to be robust, well-documented, and independently testable.

πŸ“ PROJECT STRUCTURE

project_name/
β”œβ”€β”€ src/project_name/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ core/
β”‚   └── utils/
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ unit/
β”‚   └── integration/
└── pyproject.toml

βœ… DEVELOPMENT CHECKLIST

Before every commit:

  • English only in all code/comments
  • Type annotations on all functions
  • Docstrings on public functions
  • Tests updated/added for changes
  • ruff check . --fix passes
  • ruff format . passes
  • mypy src/ passes
  • pytest passes
  • Staged files explicitly (NO git add .)
  • Atomic commit (one feature only)
  • Clean commit message (no test/chat references)

πŸš€ QUICK COMMANDS

# Setup
uv sync

# Pre-commit checks (RUN ALL)
uv run ruff check . --fix
uv run ruff format .
uv run mypy src/
uv run pytest

# Proper git workflow
git status
git diff
git add src/specific_file.py
git add tests/test_file.py
git commit -m "feat: description"

REMEMBER: These are RULES, not suggestions. Follow them strictly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment