通过在部分中附加各种注释来混合代码文档和代码?

Mixing code documentation with code by appending various notes to sections?

考虑以下最小示例:


docs/index.rst

* :ref:`modindex`

docs/modules.rst

exampleproject
==============

.. toctree::
   :maxdepth: 4

   exampleproject

.. print_notes_attached_to_topic::
   :topic: notes_about_someproblem

docs/conf.py

extensions = ['sphinx.ext.autodoc']

docs/exampleproject.rst

exampleproject package
======================

Module contents
---------------

.. automodule:: exampleproject
   :members:
   :undoc-members:
   :show-inheritance:

exampleproject/__init__.py

def example_fun():
    """
    This is the docstring I'll be discussing.
    .. attach_to_topic::
       :topic: notes_about_someproblem
       
       Grass is green.
    """
    pass

def other_example_fun():
    """
    This is the second docstring I'll be discussing.
    .. attach_to_topic::
       :topic: notes_about_someproblem
       
       Sky is blue.
    """
    pass


我知道 sphinx.ext.autodoc 可以提取文档字符串并将它们放在 docs/exampleproject.rst 中。我的问题是:有没有一种方法可以自动将某些部分附加到特定文档?理想情况下,我希望将尽可能多的文档放在源代码中,然后使用文档的源文件将这些信息按线性顺序排列。类似于:

  1. in example_fun docstring in exampleproject/__init__.py,写表达式“add a note to a section/topic named building_methods saying 'before running the project, do xyz'”
  2. 在 index.rst 中,“列出与名为 building_methods 的 section/topic 关联的所有笔记”。

与 autodoc 的比较

我知道 sphinx sphinx.ext.autodoc 可以处理应用程序的文档字符串。问题是 autodoc 强制文档的某种“代码优先”/“API-优先”结构。我正在寻找的是一种解决方案,它可以让我在代码中保留尽可能多的文档,然后将此文档转换为线性文档,其中包含从示例 attach_to_topic 之类的内容中提取的有关某些主题的数据指令。


狮身人面像可以吗?

我同意 mzjn 的观点,您的示例并没有提供太多可以继续的内容,但我会冒险进行一些猜测:

附加到 apidoc 存根页面

docs/exampleproject.rstdocs/modules.rst 存根文件由 sphinx-apidoc 自动生成。 然后您手动将自己的内容(.. print_notes_attached_to_topic:: 指令)附加到那些内容中。

这会有问题,因为每次 sphinx-apidoc 提取 Python 文档字符串以重建其存根页面时,您的块是 overwritten/lost。 我永远不会尝试通过扩展将我自己的内容混合到页面 owned/generated - 它们可以并排放置,但分开,例如将所有指令放在 ./docs/all-my-print-notes.rst 页面中。

也就是说,如果你想让你的生活复杂化,那么 post-过程。修改 Sphinx makefile 以检测存根页面更改并触发 Bash 或 Python 脚本,该脚本会在末尾弹出您的自定义内容。 如果间接完成则最干净——单个 include 指令进入存根页面,以便您的自定义内容可以在其他地方保持隔离。

autodocautosummaryJinja2 templates(在 ./site-packages/sphinx/templates/apidoc/./site-packages/sphinx/ext/autosummary/templates/ 中)提供有限的自定义,但实际上仅适用于布局和静态内容.

您的 Sphinx 扩展

您想要的功能听起来很像 sphinx.ext.todo。您的 .. attach_to_topic:: 指令分散在整个 Python 模块文档字符串中(相当于 .. todo:: 指令)并且您的 .. print_notes_attached_to_topic:: 指令将这些块收集成“线性顺序”(相当于 .. todolist::).

幸运的是,docs about creating extensions 给出了您可以根据需要进行调整的示例。您的扩展将有一个额外的功能,因为它为每个 .. todo:: 项目提供 :topic: 选项,并且还限制每个 .. todolist:: 排序规则的范围。