Python documentation generator sphinx

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

The Sphinx documentation generator

License

sphinx-doc/sphinx

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.rst

Sphinx makes it easy to create intelligent and beautiful documentation.

Sphinx uses reStructuredText as its markup language, and many of its strengths come from the power and straightforwardness of reStructuredText and its parsing and translating suite, the Docutils.

  • Output formats: HTML, PDF, plain text, EPUB, TeX, manual pages, and more
  • Extensive cross-references: semantic markup and automatic links for functions, classes, glossary terms and similar pieces of information
  • Hierarchical structure: easy definition of a document tree, with automatic links to siblings, parents and children
  • Automatic indices: general index as well as a module index
  • Code highlighting: automatic highlighting using the Pygments highlighter
  • Templating: Flexible HTML output using the Jinja 2 templating engine
  • Extension ecosystem: Many extensions are available, for example for automatic function documentation or working with Jupyter notebooks.
  • Language Support: Python, C, C++, JavaScript, mathematics, and many other languages through extensions.

For more information, refer to the the documentation.

The following command installs Sphinx from the Python Package Index. You will need a working installation of Python and pip.

We appreciate all contributions! Refer to the contributors guide for information.

About

The Sphinx documentation generator

Источник

Automatic documentation generation from code¶

In the previous section of the tutorial you manually documented a Python function in Sphinx. However, the description was out of sync with the code itself, since the function signature was not the same. Besides, it would be nice to reuse Python docstrings in the documentation, rather than having to write the information in two places.

Fortunately, the autodoc extension provides this functionality.

Reusing signatures and docstrings with autodoc¶

To use autodoc, first add it to the list of enabled extensions:

extensions = [ 'sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', ] 

Next, move the content of the .. py:function directive to the function docstring in the original Python file, as follows:

def get_random_ingredients(kind=None): """  Return a list of random ingredients as strings.   :param kind: Optional "kind" of ingredients.  :type kind: list[str] or None  :raise lumache.InvalidKindError: If the kind is invalid.  :return: The ingredients list.  :rtype: list[str]   """  return ["shells", "gorgonzola", "parsley"] 

Finally, replace the .. py:function directive from the Sphinx documentation with autofunction :

you can use the ``lumache.get_random_ingredients()`` function: .. autofunction:: lumache.get_random_ingredients 

If you now build the HTML documentation, the output will be the same! With the advantage that it is generated from the code itself. Sphinx took the reStructuredText from the docstring and included it, also generating proper cross-references.

You can also autogenerate documentation from other objects. For example, add the code for the InvalidKindError exception:

class InvalidKindError(Exception): """Raised if the kind is invalid.""" pass 

And replace the .. py:exception directive with autoexception as follows:

or ``"veggies"``. Otherwise, :py:func:`lumache.get_random_ingredients` will raise an exception. .. autoexception:: lumache.InvalidKindError 

And again, after running make html , the output will be the same as before.

Generating comprehensive API references¶

While using sphinx.ext.autodoc makes keeping the code and the documentation in sync much easier, it still requires you to write an auto* directive for every object you want to document. Sphinx provides yet another level of automation: the autosummary extension.

The autosummary directive generates documents that contain all the necessary autodoc directives. To use it, first enable the autosummary extension:

extensions = [ 'sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', ] 

Next, create a new api.rst file with these contents:

API === .. autosummary:: :toctree: generated lumache

Remember to include the new document in the root toctree:

Contents -------- .. toctree:: usage api 

Finally, after you build the HTML documentation running make html , it will contain two new pages:

Summary page created by autosummary

  • api.html , corresponding to docs/source/api.rst and containing a table with the objects you included in the autosummary directive (in this case, only one).
  • generated/lumache.html , corresponding to a newly created reST file generated/lumache.rst and containing a summary of members of the module, in this case one function and one exception.

Each of the links in the summary page will take you to the places where you originally used the corresponding autodoc directive, in this case in the usage.rst document.

The generated files are based on Jinja2 templates that can be customized , but that is out of scope for this tutorial.

Источник

Генератор документации Sphinx¶

В руководстве подробно описан процесс генерации документации с помощью связки reStructuredText, Python Sphinx, GitHub и сервиса Read the Docs.

Последняя правка: окт. 08, 2017

  • Предисловие
    • О чём данное руководство?
    • Почему именно Sphinx?
    • Структура книги
    • Рекомендации
    • Авторские права
    • Дата публикации и версия программного обеспечения
    • Обратная связь
    • Быстрый старт
      • Установка
      • Создание нового проекта
      • Файл index
      • Генерация документа
      • Добавление иллюстраций
      • Автоматическая сборка
      • Изменение названия и копирайта
      • Строки Unicode
      • Версии публикации
      • Настройка локализации
      • Настройка отображения даты
      • Подключение расширений
      • Режим отображения формул
      • Добавление favicon
      • Метаданные. Тег META
      • Смена HTML-темы
      • Преамбула
      • Язык и кодировка
      • Уровни заголовков в содержании
      • Настройка языка
      • Отключение копирайта
      • Отключение надписи “Created using Sphinx”
      • Настройка отображения URL-адресов
      • Настройка глубины содержания
      • Настройка названия и заголовка
      • Что такое reStructuredText?
      • Редакторы reStructuredText
        • ReText
        • SublimeText
        • Online reStructuredText editor
        • NoTex.ch
        • rstext.me
        • Базовые концепции
        • Абзацы
        • Заголовки
        • Начертание
        • Нумерованные списки
        • Маркированные списки
        • Вложенные списки
        • Верхний и нижние индексы
        • Определения
        • Цитаты
        • Эпиграф
        • Сноски
        • Комментарии
        • Листинги (исходный код)
        • Автозамены (Подстановки)
        • Использование символов юникод (unicode)
        • Дата и время
        • Вставка текста из других файлов
        • Черта (Линия)
        • Ссылки
        • Изображения и иллюстрации
        • Таблицы
        • Формулы
        • Блоки примечаний и предупреждений
        • Содержание
        • Метаданные. Тег META
        • Автоматическое содержание
        • Примеры исходного кода с подсветкой синтаксиса
          • Вставка примеров кода из файла
          • Нумерация формул
          • Отображение формул
          • Вставка графиков
          • Ссылки на разделы
          • Ссылки на изображения
          • Ссылки на таблицы
          • Ссылки на формулы
          • Глоссарий
          • Аббревиатуры
          • Пункты меню
          • Автозамены Sphinx (Подстановки)
          • Смотрите также
          • Боковая врезка
          • Рубрики
          • Горизонтальный список
          • Документация по языкам программирования
Оцените статью