К основному содержанию
правило

sphinx — правило для Cursor: документация Python на Sphinx

Правило задаёт Cursor порядок работы с документацией Python: структура docs/, MyST, docstring в стиле Google и автогенерация API. Пригодится, когда проект уже оброс модулями, а документация живёт в голове автора.

Установить в Cursor · Вручную: положить файлы Все способы и платформы ↓
.cursor/rules/sphinx.mdc
Открыть на GitHub

Что делает sphinx

Правило срабатывает на файлы **/*.py и описывает, как вести документацию проекта на Sphinx. Сборку советует держать в отдельном виртуальном окружении, чтобы зависимости документации не смешивались с рабочими. Исходники — в каталоге docs/ в корне проекта, рядом conf.py, index.md, подпапки tutorial/ и api/.

Для нового текста правило выбирает MyST Markdown, а не reStructuredText: в conf.py включается myst_parser и расширение source_suffix. API тянется из кода через sphinx.ext.autodoc и autosummary, docstring пишутся в стиле Google с аннотациями типов, их разбирает sphinx.ext.napoleon. Навигация строится директивой toctree в index.md, внешние ссылки — через intersphinx с картой intersphinx_mapping.

Отдельный пункт — про sphinx-apidoc: запускать один раз для каркаса .rst, но не давать перезаписывать написанное руками. Если гонять sphinx-apidoc -o api/ ../my_package без исключений на каждый билд, ручные правки в api/ пропадут. Живой предпросмотр во время работы даёт sphinx-autobuild.

Какие задачи решает

  • разложить исходники документации по каталогам docs/, tutorial/ и api/
  • включить MyST Markdown и собирать .md вместе с .rst
  • вытащить API-справку из docstring без ручного копирования
  • связать текст с документацией Python, NumPy и Requests через intersphinx
  • защитить отредактированные файлы api/ от перезаписи при повторном запуске sphinx-apidoc

Примеры запросов агенту

  • Разложи документацию по каталогам docs/, tutorial/ и api/ и заведи conf.py с myst_parser.
  • Собери API-справку из docstring модуля my_package.module через autodoc и autosummary.
  • Добавь в docs/index.md директиву toctree с tutorial и api и настрой intersphinx_mapping.

Как установить sphinx

Вручную: положить файлы

.cursor/rules/sphinx.mdc

Во frontmatter: description, globs, alwaysApply

По шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules

Вопросы о sphinx

Как установить правило sphinx в Cursor?

Скопируйте файл правила в .cursor/rules/sphinx.mdc в корне проекта. Cursor подхватит его автоматически.

Что делает правило sphinx?

Задаёт структуру каталога docs/, настройки conf.py и порядок генерации API-справки из docstring. Работает как свод договорённостей по документации Python-проекта.

Почему sphinx-apidoc нельзя запускать при каждой сборке?

Он перезаписывает файлы в каталоге вывода. Правило советует прогнать его один раз для каркаса, а дальше править .rst вручную и держать ручные материалы вне каталога api/.

Исходный текст

sphinx.mdc · CC0-1.0
---
description: This rule file provides opinionated, practical guidelines for setting up, writing, and maintaining Python project documentation using Sphinx, emphasizing modern best practices, clear structure, and automated validation.
globs: **/*.py
---
# Sphinx Best Practices

Sphinx is the definitive tool for Python project documentation. This guide outlines the essential workflow and best practices for creating intelligent, beautiful, and maintainable docs. Always prioritize consistency within your project over strict adherence to external guides, but default to these modern standards.

## 1. Project Setup and Structure

Establish a clean, predictable documentation structure from the start.

### 1.1. Use a Virtual Environment

Always isolate your documentation build dependencies. This prevents conflicts and ensures reproducible builds.

```bash
# ❌ BAD: Installing Sphinx globally
pip install sphinx

# ✅ GOOD: Create and activate a virtual environment
python -m venv .venv/docs
source .venv/docs/bin/activate  # On Windows: .venv\docs\Scripts\activate
pip install sphinx sphinx-autobuild myst-parser sphinx-rtd-theme sphinx.ext.napoleon
```

### 1.2. Standard Directory Layout

Place all documentation source files in a dedicated `docs/` directory at your project root.

```
my_project/
├── .venv/
├── my_package/
│   └── __init__.py
│   └── module.py
├── docs/
│   ├── conf.py
│   ├── index.md        # Or index.rst
│   ├── tutorial/       # For manual narrative content
│   │   └── getting_started.md
│   ├── api/            # For auto-generated API docs (managed by apidoc)
│   │   └── my_package.rst
│   ├── _static/        # Custom static files (images, CSS)
│   ├── _templates/     # Custom Jinja2 templates
│   └── Makefile        # Or make.bat for Windows
├── README.md
├── CHANGELOG.md
├── LICENSE
└── pyproject.toml
```

### 1.3. Initialize with `sphinx-quickstart`

Use the quickstart tool once to scaffold your `docs/` directory. Accept the defaults, then customize.

```bash
# From your project root:
cd docs
sphinx-quickstart
```

### 1.4. Prefer MyST Markdown for New Content

For narrative documentation, MyST Markdown (`.md`) is more approachable than reStructuredText (`.rst`) while retaining Sphinx's powerful features. Use it for all new manual content.

**`docs/conf.py`:**

```python
# ✅ GOOD: Enable MyST Parser
extensions = [
    'myst_parser',
    # ... other extensions
]
source_suffix = {
    '.rst': 'restructuredtext',
    '.md': 'markdown',
}
```

## 2. Docstring Conventions and API Generation

Generate API documentation directly from your Python code's docstrings.

### 2.1. Adopt Google-Style Docstrings with Type Hints

Write docstrings in Google style for clarity and consistency. Always include type hints in your function/method signatures. The `sphinx.ext.napoleon` extension will parse these automatically.

**`docs/conf.py`:**

```python
# ✅ GOOD: Enable Napoleon for Google/NumPy style docstrings
extensions = [
    # ... other extensions
    'sphinx.ext.napoleon',
]
napoleon_google_docstring = True
napoleon_numpy_docstring = False # Stick to one style
napoleon_use_param = True
napoleon_use_rtype = True
```

**`my_package/module.py`:**

```python
# ❌ BAD: Inconsistent, missing types, hard to parse
def calculate_sum(a, b):
    """Adds two numbers."""
    return a + b

# ✅ GOOD: Google-style, type-hinted docstring
def calculate_sum(a: int, b: int) -> int:
    """Calculate the sum of two integers.

    Args:
        a: The first integer.
        b: The second integer.

    Returns:
        The sum of `a` and `b`.
    """
    return a + b
```

### 2.2. Automate API Documentation with `autodoc` and `autosummary`

Use `sphinx.ext.autodoc` to pull docstrings and `sphinx.ext.autosummary` to generate clean API tables.

**`docs/conf.py`:**

```python
# ✅ GOOD: Enable core API extensions
extensions = [
    # ... other extensions
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
]
autodoc_member_order = 'bysource' # Keep members in source order
autodoc_typehints = 'signature'   # Show type hints in signatures
autosummary_generate = True       # Automatically generate stub files
```

**`docs/api/index.rst` (or `.md` with MyST directives):**

```rst
.. automodule:: my_package.module
   :members:

.. autosummary::
   :toctree: _autosummary
   :template: module.rst

   my_package.module.calculate_sum
   my_package.module.MyClass
```

### 2.3. Manage `sphinx-apidoc` Carefully

Run `sphinx-apidoc` once to scaffold API `.rst` files. **Never let it overwrite your manual documentation.**

```bash
# From docs/ directory:
# ❌ BAD: Running apidoc without exclusion, risks overwriting manual content
sphinx-apidoc -o api/ ../my_package

# ✅ GOOD: Run apidoc once, then manually integrate and exclude.
# First run (from docs/):
sphinx-apidoc -o api/ ../my_package -f -e -M

# Then, add 'api/' to your master toctree in index.md/rst.
# Manually edit generated files (e.g., api/modules.rst) to include specific modules.
# Add 'api/my_package.rst' to `exclude_patterns` in conf.py if you want to prevent
# apidoc from regenerating *that specific file* on subsequent runs,
# but generally, it's better to let apidoc manage its own output directory
# and only exclude specific files if they are manually edited.
# For manual tutorials, ensure they are in a separate directory (e.g., `tutorial/`)
# and *not* in the apidoc output directory.
```

## 3. Content Management and Cross-Referencing

Structure your documentation logically and enable seamless navigation.

### 3.1. Master `toctree` for Structure

Organize your documentation using the `toctree` directive in your main `index.md` (or `index.rst`).

**`docs/index.md`:**

```markdown
# My Project Documentation

Welcome to the documentation for My Project!

```{toctree}
:maxdepth: 2
:caption: Contents:

tutorial/getting_started
api/index
```

### 3.2. Link External Projects with `intersphinx`

Easily link to documentation of other Python projects (e.g., Python, NumPy, Django).

**`docs/conf.py`:**

```python
# ✅ GOOD: Enable intersphinx and define mappings
extensions = [
    # ... other extensions
    'sphinx.ext.intersphinx',
]

intersphinx_mapping = {
    'python': ('https://docs.python.org/3/', None),
    'numpy': ('https://numpy.org/doc/stable/', None),
    'requests': ('https://requests.readthedocs.io/en/latest/', None),
}
```

**`docs/tutorial/getting_started.md`:**

```markdown
# Getting Started

This project uses [Python's built-in `list` type](:py:class:`python:list`).
For network requests, we rely on the [Requests library](:py:mod:`requests:requests`).
```

## 4. Building and Testing Documentation

Integrate documentation builds into your development and CI workflow.

### 4.1. Use `sphinx-autobuild` for Live Previews

During development, `sphinx-autobuild` provides live-reloading previews, accelerating your writing process.

```bash
# From docs/ directory:
# ✅ GOOD: Live preview with automatic rebuild on file changes
sphinx-autobuild . _build/html --port 8000
```

### 4.2. Integrate Docs Build into CI/CD

Ensure your documentation builds successfully and is up-to-date by including a build step in your CI pipeline. Treat documentation errors as build failures.

**`.github/workflows/ci.yml` (Example for GitHub Actions):**

```yaml
# ✅ GOOD: Build docs in CI
name: CI

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.x'
    - name: Install dependencies
      run: |
        python -m venv .venv/docs
        source .venv/docs/bin/activate
        pip install -e .[docs] # Install project and docs dependencies
    - name: Build Sphinx documentation
      run: |
        source .venv/docs/bin/activate
        cd docs
        make html # Or sphinx-build -W -b html . _build/html
```

### 4.3. Enforce Docstring Style and Quality

Use linters like `pydocstyle` to enforce PEP 257 docstring conventions and `flake8` for general PEP 8 compliance.

```bash
# ✅ GOOD: Linting for code and docstrings
pip install flake8 pydocstyle

# In your CI or pre-commit hook:
flake8 my_package/
pydocstyle my_package/
```

### 4.4. Test Docstring Examples with `doctest`

Embed simple, runnable examples in your docstrings and use `sphinx.ext.doctest` to verify them.

**`docs/conf.py`:**

```python
# ✅ GOOD: Enable doctest
extensions = [
    # ... other extensions
    'sphinx.ext.doctest',
]
```

**`my_package/module.py`:**

```python
def multiply(a: int, b: int) -> int:
    """Multiply two integers.

    >>> multiply(2, 3)
    6
    >>> multiply(0, 5)
    0
    """
    return a * b
```

## 5. Packaging and Distribution

Ensure your documentation is easily accessible and distributable.

### 5.1. Host on Read the Docs

Read the Docs provides free, automated hosting for Sphinx documentation, integrating directly with your version control system. Configure it to build on every commit.

### 5.2. Include Docs in Source Distribution

If your documentation is essential for offline use or specific deployment scenarios, ensure it's included in your project's source distribution.

**`pyproject.toml` (or `MANIFEST.in` for older projects):**

```toml
# ✅ GOOD: Include docs in source distribution
[tool.setuptools.package-data]
"my_package" = ["py.typed"] # Example for type hints
"my_project" = ["docs/*"] # Include entire docs directory
```

© sanjeed5 · CC0-1.0 · sanjeed5/awesome-cursor-rules-mdc

Похожие правила IDE

Все правила IDE по теме «Тексты и документация» →
use-cliche-data-in-docs официальный github Правило помогает писать документацию и примеры с вымышленными данными вместо значений из конфигов, скриптов и запросов. Пригодится при создании и правке документации. ★ 40 451звёзд репо update-docs-on-code-change официальный github Правило для GitHub Copilot, которое напоминает обновлять README.md и документацию, когда меняется код. Пригодится, если доки у вас отстают от реальности. ★ 40 451звёзд репо spec-driven-workflow-v1 официальный github Правило ведёт разработку от формулировки требований к проектированию, реализации и проверке. Пригодится, когда нужно фиксировать решения и ход работы в отдельных файлах. ★ 40 451звёзд репо power-apps-canvas-yaml официальный github Правило помогает Copilot работать с YAML-файлами Canvas Apps и формулами Power Fx. Пригодится при правке экранов, компонентов и источников данных приложения. ★ 40 451звёзд репо pcf-manifest-schema официальный github Правило подсказывает Copilot структуру ControlManifest.Input.xml: какие элементы и атрибуты бывают и что они делают. Пригодится, когда правишь манифест PCF-компонента. ★ 40 451звёзд репо markdown официальный github Правило помогает GitHub Copilot писать и проверять Markdown-файлы по CommonMark 0.31.2. Оно применяется к файлам .md. ★ 40 451звёзд репо

Из того же набора79

tauri Правило для Cursor задаёт, как писать Rust-бэкенд в Tauri: команды, глобальное состояние, ошибки и безопасность. Пригодится, когда фронтенд уже есть, а Rust-часть растёт. ★ 3 579звёзд репо svelte Правило для Cursor задаёт, как писать компоненты Svelte 5: руны вместо старой реактивности, типизация и ключи в списках. Пригодится, если проект уже на Svelte 5. ★ 3 579звёзд репо streamlit Правило для Cursor задаёт, как писать приложения на Streamlit: кэшировать тяжёлые операции, держать UI отдельно от логики и разбивать проект на модули. ★ 3 579звёзд репо sqlalchemy Правило для Cursor задаёт стиль SQLAlchemy 2.x: типизированные модели, сессии через контекстный менеджер, select() вместо устаревшего Query. ★ 3 579звёзд репо solidity Правило задаёт стиль и требования к Solidity-коду: фиксированный pragma, кастомные ошибки, защита от реентрантности. Пригодится, когда пишете контракты в Cursor. ★ 3 579звёзд репо shadcn Правило для Cursor задаёт команде единый стиль работы с shadcn/ui: структура папок, типы, варианты через CVA, формы на React Hook Form и Zod. Пригодится, когда компонентов становится много. ★ 3 579звёзд репо sentry Правило задаёт, как инициализировать Sentry в проекте: где ставить SDK, какие переменные окружения использовать, как не сломать чужой код. ★ 3 579звёзд репо scrapy Правило с набором практик для Scrapy: структура проекта, items, pipelines, middlewares. Пригодится, когда агент пишет парсеры на Python. ★ 3 579звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой