You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Sphinx autodoc将模块文档字符串标题转为侧边栏可展开章节?

问题描述

我有两个Python模块:

Module 1

"""
Module 1
=========
"""
def foo():
    """foo doc"""

Module 2

"""
Module 2
=========
"""
def bar():
    """bar doc"""

最初编写的RST文件如下:

*************
Some heading
*************

.. automodule:: package.module1
    :members:

.. automodule:: package.module2
    :members:

构建后侧边栏结构是:

[+] Some Heading
    Module 1
    foo        
    Module 2
    bar

模块文档字符串里的标题和模块成员处于同一层级,不符合需求。而把模块标题移到RST文件后:

*************
Some heading
*************

Module 1
=========

.. automodule:: package.module1
    :members:

Module 2
=========

.. automodule:: package.module2
    :members:

能得到预期的可展开结构:

[+] Some Heading
    [+] Module 1
        foo 
    [+] Module 2
        func1
        bar

想知道如何通过autodoc或Sphinx直接将模块文档字符串中的标题转为侧边栏的可展开章节,不用手动把标题移到RST文件里。

解决方案

可以通过以下两种方式实现:

1. 自定义autodoc处理函数

在Sphinx的配置文件conf.py中添加自定义逻辑,自动提取模块文档字符串中的RST格式标题,将其转换为层级标题后,再渲染模块成员内容:

from sphinx.ext.autodoc import ModuleDocumenter

class CustomModuleDocumenter(ModuleDocumenter):
    def generate(self, *args, **kwargs):
        # 提取模块文档字符串中的标题
        docstring = self.object.__doc__ or ""
        lines = docstring.split('\n')
        title = None
        underline = None
        
        if len(lines) >= 2:
            candidate_title = lines[0].strip()
            candidate_underline = lines[1].strip()
            # 判断是否为标准RST标题(下划线由=、-、~等符号组成)
            if candidate_underline and all(c in '=-~^' for c in candidate_underline):
                title = candidate_title
                underline = candidate_underline
                # 移除文档字符串中的标题行,避免重复渲染
                self.object.__doc__ = '\n'.join(lines[2:]).strip()
        
        # 先输出提取到的标题和下划线
        if title and underline:
            self.add_line(title, '<autodoc>')
            self.add_line(underline, '<autodoc>')
            self.add_line('', '<autodoc>')
        
        # 调用原生方法生成模块成员内容
        super().generate(*args, **kwargs)

def setup(app):
    app.add_autodocumenter(CustomModuleDocumenter)

添加后,autodoc会自动将模块文档字符串中的标题转为层级标题,模块成员会嵌套在该标题下,最终在侧边栏形成可展开的章节结构。

2. 结合autosummary自定义模板

如果项目使用autosummary,可以通过自定义模板实现需求:

  1. 在Sphinx项目的_templates/autosummary/目录下创建module.rst文件,内容如下:
{{ fullname | escape | underline}}

{% block module_doc %}
{{ objname | escape | underline}}

{{ module_doc }}
{% endblock %}

{% block functions %}
{% if functions %}
Functions
---------

{% for item in functions %}
* :func:`{{ item }}`
{% endfor %}
{% endif %}
{% endblock %}
  1. 在主RST文件中使用autosummary生成模块文档:
*************
Some heading
*************

.. autosummary::
    :toctree: generated
    :recursive:

    package.module1
    package.module2

这种方式会自动提取模块文档字符串中的标题作为层级标题,将成员内容嵌套在下方,形成侧边栏的可展开结构。

内容的提问来源于stack exchange,提问作者MaxPowers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:33:31