Python Sphinx移除外部模块文档:解决属性重复显示问题
Sphinx生成Kivy代码文档时属性重复显示的解决办法
问题背景
使用Sphinx为基于Kivy框架的Python代码生成文档时,MyApp类中声明的string(StringProperty类型类属性)会在生成的文档中重复出现:
- 一次是类文档字符串
Attributes部分的自定义描述 - 一次是Sphinx自动引入的Kivy模块中
StringProperty的默认文档
需要仅保留自定义的文档内容,移除自动添加的外部模块相关文档。
解决方法
方法一:排除指定属性的自动文档提取
在main.rst的automodule指令中添加:exclude-members:参数,排除string属性,让文档仅显示类文档字符串中自定义的描述:
main module =========== .. automodule:: main :members: :undoc-members: :show-inheritance: :exclude-members: string
方法二:直接为属性添加文档字符串
去掉类文档字符串中Attributes部分的string描述,转而直接在string属性下方添加文档字符串,这样Sphinx会提取该自定义文档而非Kivy的默认文档:
class MyApp(App): """ Description. Attributes ---------- layout : FloatLayout the widget returned in the build method """ string = StringProperty("") """StringProperty: Some string."""
方法三:全局关闭文档字符串继承
在conf.py中添加autodoc_inherit_docstrings = False,禁止Sphinx继承外部类(如Kivy的StringProperty)的文档字符串。注意此设置为全局生效,会影响所有类的文档生成:
# -- General configuration --------------------------------------------------- extensions = ['sphinx.ext.todo', 'sphinx.ext.viewcode', 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx_mdinclude'] # 添加以下配置项 autodoc_inherit_docstrings = False templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
内容的提问来源于stack exchange,提问作者Abel Gutiérrez
相关产品推荐
相关产品推荐

