如何让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,可以通过自定义模板实现需求:
- 在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 %}
- 在主RST文件中使用
autosummary生成模块文档:
************* Some heading ************* .. autosummary:: :toctree: generated :recursive: package.module1 package.module2
这种方式会自动提取模块文档字符串中的标题作为层级标题,将成员内容嵌套在下方,形成侧边栏的可展开结构。
内容的提问来源于stack exchange,提问作者MaxPowers
相关产品推荐
相关产品推荐

