如何使用Sphinx对函数参数进行分组展示
如何使用Sphinx对函数参数进行分组展示
嘿,我完全理解你想把函数参数按类别分组展示的需求——这样文档结构更清晰,用户一眼就能找到对应类型的参数!你之前遇到的参数重复显示问题,是因为Sphinx默认会收集所有:param:标签并生成一个统一的Parameters小节,加上你手动写的分组,就导致了重复输出。下面给你两种可行的解决办法:
方法一:用原生reStructuredText自定义分组(无需额外扩展)
这种方法不用依赖任何扩展,直接通过rubric标题和自定义列表来实现分组,避免Sphinx自动生成重复的参数列表。你可以把docstring改成这样:
def myfunc(from_date, until_date, col_color, col_taste): """ Gets data from the desired period and returns them as a dataframe. .. rubric:: Selection parameters - **from_date**: First date of the period to be selected. - **until_date**: Last date of the period to be selected. .. rubric:: Content parameters - **col_color**: Whether to include the color column in the output. - **col_taste**: Whether to include the taste column in the output. """ # 函数实现逻辑
这里用.. rubric::来创建分组标题,然后用带加粗参数名的列表来描述每个参数。这样Sphinx就不会自动生成默认的Parameters小节,只会显示你自定义的分组内容,完美解决重复问题。另外提醒一下:from是Python的关键字,不能用作参数名,我改成了from_date,你记得调整哦。
方法二:用Napoleon扩展支持自定义分组(更灵活)
如果你习惯用Google/NumPy风格的docstring,或者想要保留参数标签的自动格式化,可以用Sphinx的sphinx.ext.napoleon扩展来实现自定义分组。
步骤1:启用Napoleon扩展
先在你的conf.py里添加Napoleon扩展:
extensions = [ # 其他扩展... 'sphinx.ext.napoleon', ]
步骤2:配置自定义分组
在conf.py里添加自定义分组的配置,告诉Napoleon识别你的分组名称:
napoleon_custom_sections = ['Selection parameters', 'Content parameters']
步骤3:编写分组后的docstring
现在你可以用Google风格的docstring来分组参数了:
def myfunc(from_date, until_date, col_color, col_taste): """ Gets data from the desired period and returns them as a dataframe. Selection parameters: from_date: First date of the period to be selected. until_date: Last date of the period to be selected. Content parameters: col_color: Whether to include the color column in the output. col_taste: Whether to include the taste column in the output. """ # 函数实现逻辑
这样Napoleon会自动把这些自定义分组解析成Sphinx能识别的结构,生成的文档里参数就会按你设置的分组展示,不会重复。
备注:内容来源于stack exchange,提问作者Antonio Serrano
相关产品推荐
相关产品推荐

