文档开发工具【免费下载链接】sphinxThe Sphinx documentation generator项目地址https://gitcode.com/gh_mirrors/sp/sphinx点击查看免费下载导读本文围绕 Sphinx 仓库自带的 Google 风格 Docstring 示例页 及其配套源码 example_google.py 展开系统讲解如何用sphinx.ext.napoleon扩展解析 Google 风格 docstring 并生成结构化 API 文档。读完本文你将掌握 Google 风格 docstring 的模块级、函数级、类级写法规范、与 PEP 484/526 类型注解的配合方式、Napoleon 全部配置项的语义以及该解析机制在源码层面的工作原理可直接套用于自己的项目。这份示例文档是什么doc/usage/extensions/example_google.rst是一份被标记为:orphan:的独立页面不会自动进入文档目录树它的作用是完整展示用 Google Python 风格指南撰写 docstring 的模块长什么样。页面主体只有三个动作通过:ref:example_numpy 在 seealso 中指向 NumPy 风格示例页方便读者对照两种风格仅在 HTML 构建器下.. only:: builder_html提供:download:下载链接指向example_google.py本身通过literalinclude指令把 example_google.py 的完整源码原样嵌入页面并以:language: python声明语法高亮。也就是说这份文档的真正技术内容全部沉淀在示例源码里。该示例与 napoleon.rst 中的 Napoleon 扩展文档互为表里前者提供符合规范的 docstring 全文后者解释这些 docstring 会被如何解析和渲染。启用 Napoleon 的前置条件Napoleon 是 Sphinx 的官方扩展自 Sphinx 1.3 起提供作用是解析 Google 与 NumPy 两种风格的 docstring。启用方式是在conf.py中加入# conf.py extensions [sphinx.ext.napoleon]随后可用sphinx-apidoc从项目目录生成 API 文档骨架$ sphinx-apidoc -f -o docs/source projectdirNapoleon 是一个预处理器它在 Sphinx 解析 docstring 之前先把 Google/NumPy 风格内容转换成 reStructuredText再交给 docutils 处理。转换发生在构建的中间步骤不会修改源文件里的任何 docstring。因此凡是sphinx.ext.autodoc能找到的 docstring——模块、类、属性、方法、函数、变量——都会经过 Napoleon 的解释。模块级 Docstring如何描述整个模块示例模块的 docstring 首先给出摘要与扩展描述然后说明该文档遵循 Google Python 风格指南并提示docstring 可跨多行节section由『节标题 冒号 缩进文本块』构成Example Google style docstrings. This module demonstrates documentation as specified by the Google Python Style Guide_. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text. Example: Examples can be given using either the Example or Examples sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts.这段文字同时示范了两条关键规则Example/Examples节用于给出示例节体内可以使用任何 reStructuredText 格式包括::引入的字面量块节的分隔规则Google 风格依靠缩进划分节——恢复非缩进文本即表示上一个节结束任何新节开始也隐式终结当前节。随后模块 docstring 用Attributes节说明模块级变量并用Todo节声明待办事项Attributes: module_level_variable1 (int): Module level variables may be documented in either the Attributes section of the module docstring, or in an inline docstring immediately following the variable. Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it. Todo: * For module TODOs * You have to also use sphinx.ext.todo extension示例特意指出Todo节要真正渲染出来还必须在conf.py中同时启用sphinx.ext.todo扩展——这是节支持与扩展渲染互相配合的典型体现。模块级变量的两种文档化方式示例通过两个真实变量演示了两种等价写法并强调两种方式都可用但同一项目不要混用module_level_variable1 12345 module_level_variable2 98765 int: Module level variable documented inline. The docstring may span multiple lines. The type may optionally be specified on the first line, separated by a colon. module_level_variable1在模块 docstring 的Attributes节里统一说明module_level_variable2紧随变量声明之后用独立 docstring 内联说明类型写在第一行并用冒号分隔。函数 DocstringArgs、Returns 与 Raises类型写在 docstring 里的写法当函数没有使用 PEP 484 注解时类型信息需要直接写进 docstringdef function_with_types_in_docstring(param1, param2): Example function with types documented in the docstring. :pep:484 type annotations are supported. If attribute, parameter, and return types are annotated according to PEP 484_, they do not need to be included in the docstring: Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. 参数条目遵循name (type): description格式返回条目则是type: description类型可选。使用 PEP 484 注解的写法若参数与返回值都已按 PEP 484 注解docstring 中就无需重复类型def function_with_pep484_type_annotations(param1: int, param2: str) - bool: Example function with PEP 484 type annotations. Args: param1: The first parameter. param2: The second parameter. Returns: The return value. True for success, False otherwise. 这样既避免信息冗余又让类型检查器和 IDE 能直接利用注解做静态分析。完整参数格式默认值、*args、**kwargs 与多行描述module_level_function展示了最完整的 Google 参数写法def module_level_function(param1, param2None, *args, **kwargs): This is an example of a module level function. Function parameters should be documented in the Args section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious. If *args or **kwargs are accepted, they should be listed as *args and **kwargs. The format for a parameter is:: name (type): description The description may span multiple lines. Following lines should be indented. The (type) is optional. Multiple paragraphs are supported in parameter descriptions. Args: param1 (int): The first parameter. param2 (:obj:str, optional): The second parameter. Defaults to None. Second line of description should be indented. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: bool: True if successful, False otherwise. The return type is optional and may be specified at the beginning of the Returns section followed by a colon. The Returns section may span multiple lines and paragraphs. Following lines should be indented to match the first line. The Returns section supports any reStructuredText formatting, including literal blocks:: { param1: param1, param2: param2, } Raises: AttributeError: The Raises section is a list of all exceptions that are relevant to the interface. ValueError: If param2 is equal to param1. if param1 param2: msg param1 may not be equal to param2 raise ValueError(msg) return True需要继承的关键规范参数名必须出现类型与描述可选但不明显时应尽量给出可变长参数以*args、**kwargs原样列出描述可跨多行续行必须缩进支持多个段落可选参数习惯标注optional如(:obj:str, optional)并说明默认值Returns节可跨多行、多段落支持任意 reStructuredText 格式包括字面量块Raises节逐一列出接口相关的异常及触发条件函数体内也确实实现了ValueError的抛出逻辑代码与文档互相印证。生成器用 Yields 代替 Returns生成器函数的输出应写在Yields节Examples节则应写成 doctest 格式可被sphinx.ext.doctest直接验证def example_generator(n): Generators have a Yields section instead of a Returns section. Args: n (int): The upper limit of the range to generate, from 0 to n - 1. Yields: int: The next number in the range of 0 to n - 1. Examples: Examples should be written in doctest format, and should illustrate how to use the function. print([i for i in example_generator(4)]) [0, 1, 2, 3] yield from range(n)异常类与类的 Docstring异常类的写法异常类按类的相同方式文档化__init__既可写进类级 docstring也可写在__init__方法自身但二者不可混用。示例选择在类级 docstring 中一并说明构造函数参数与实例属性class ExampleError(Exception): Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note: Do not include the self parameter in the Args section. Args: msg (str): Human readable string describing the exception. code (:obj:int, optional): Error code. Attributes: msg (str): Human readable string describing the exception. code (int): Exception error code. def __init__(self, msg, code): self.msg msg self.code code注意两点惯例self永远不要写进Args异常类的Args与Attributes常成对出现分别描述构造入参与最终属性。普通类的写法class ExampleClass: The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an Attributes section and follow the same formatting as a functions Args section. Alternatively, attributes may be documented inline with the attributes declaration (see __init__ method below). Properties created with the property decorator should be documented in the propertys getter method. Attributes: attr1 (str): Description of attr1. attr2 (:obj:int, optional): Description of attr2. 规范要点摘要行应在一行内收束公开属性要么集中写进类级Attributes要么内联在声明处同样不可混用property装饰的属性一律在其 getter 方法中文档化。init与实例属性的内联文档__init__自身的 docstring 与类级 docstring 二选一。示例展示了三种内联属性文档写法同时存在以作对照def __init__(self, param1, param2, param3): Example of docstring on the __init__ method. ... Args: param1 (str): Description of param1. param2 (:obj:int, optional): Description of param2. Multiple lines are supported. param3 (list(str)): Description of param3. self.attr1 param1 self.attr2 param2 self.attr3 param3 #: Doc comment *inline* with attribute #: list(str): Doc comment *before* attribute, with type specified self.attr4 [attr4] self.attr5 None str: Docstring *after* attribute, with type specified.#:注释与属性同行inline或置于属性声明之前before可含类型独立的字符串 docstring 放在属性赋值之后after可含类型类型同样遵循首行、冒号分隔的规则。property 的文档位置property def readonly_property(self): str: Properties should be documented in their getter method. return readonly_property property def readwrite_property(self): list(str): Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. return [readwrite_property] readwrite_property.setter def readwrite_property(self, value): _ value可读写属性的文档只写进 getter若 setter 有值得注意的行为也应在此提及。这样 Sphinx 渲染属性时能得到完整说明。方法 Docstring 与成员收录控制普通方法与函数规则一致同样强调self不写入Argsdef example_method(self, param1, param2): Class methods are similar to regular functions. Note: Do not include the self parameter in the Args section. Args: param1: The first parameter. param2: The second parameter. Returns: True if successful, False otherwise. return True特殊成员与私有成员的收录开关示例专门定义了几个对照成员说明默认收录行为与对应的conf.py开关def __special__(self): By default special members with docstrings are not included. Special members are any methods or attributes that start with and end with a double underscore. Any special member with a docstring will be included in the output, if napoleon_include_special_with_doc is set to True. This behavior can be enabled by changing the following setting in Sphinxs conf.py:: napoleon_include_special_with_doc True pass def __special_without_docstring__(self): pass def _private(self): By default private members are not included. Private members are any methods or attributes that start with an underscore and are *not* special. By default they are not included in the output. This behavior can be changed such that private members *are* included by changing the following setting in Sphinxs conf.py:: napoleon_include_private_with_doc True pass def _private_without_docstring__(self): pass特殊成员__name__形式默认不带 docstring 的不输出带 docstring 的需设置napoleon_include_special_with_doc True才纳入输出私有成员单下划线开头、非特殊默认一律不输出需要时设置napoleon_include_private_with_doc True。PEP 526 类属性注解ExamplePEP526Class演示了变量注解与类 docstring 配合当napoleon_attr_annotations为True时类体中用 PEP 526 语法声明的类型会被拾取因此Attributes节里可以省略类型class ExamplePEP526Class: The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an Attributes section and follow the same formatting as a functions Args section. If napoleon_attr_annotations is True, types can be specified in the class body using PEP 526 annotations. Attributes: attr1: Description of attr1. attr2: Description of attr2. attr1: str attr2: int即属性在 docstring 中未写类型、但类体内有注解时注解类型会被采用。Napoleon 支持的全部 Docstring 节除上述示例用到的节之外Napoleon 完整支持的节标题见 napoleon.rst如下节标题说明Args/ArgumentsParameters的别名Attention/Caution/Danger/Error渲染为对应 admonitionAttributes属性说明Example/Examples示例渲染方式受napoleon_use_admonition_for_examples控制Hint/Important/Note/Tip/Warning/Warnings提示类 admonitionWarnings是Warning的别名Keyword Args/Keyword Arguments关键字参数Methods方法列表Notes说明渲染方式受napoleon_use_admonition_for_notes控制Other Parameters次要参数Parameters参数Return/Returns返回值Return是别名Raise/Raises异常Raise是别名References参考资料渲染方式受napoleon_use_admonition_for_references控制See Also参见Todo待办需配合sphinx.ext.todoWarn/Warns告警Yield/Yields生成器产出Yield是别名这些节名在 sphinx/ext/napoleon/docstring.py 的_sections字典中与各自的解析函数一一对应如args/arguments映射到_parse_parameters_section、yields映射到_parse_yields_section、各 admonition 节映射到_parse_admonition。Google 风格与 NumPy 风格的区别Napoleon 同时支持两种风格核心差异在于分隔方式Google 风格用缩进划分节Args:冒号 缩进块NumPy 风格用下划线划分节Parameters标题下加等长下划线。同一函数的两种写法对比完整对照见 example_numpy.py# Google 风格 def func(arg1, arg2): Summary line. Args: arg1 (int): Description of arg1 arg2 (str): Description of arg2 Returns: bool: Description of return value return True# NumPy 风格 def func(arg1, arg2): Summary line. Parameters ---------- arg1 : int Description of arg1 arg2 : str Description of arg2 Returns ------- bool Description of return value return True经验取舍Google 风格更省纵向空间、短小 docstring 易读NumPy 风格更省横向空间、长而深入的 docstring 更易读。两者主要是审美差异但项目内应统一选择一种不要混用。Napoleon 配置项全解Napoleon 的全部配置项及默认值如下可在conf.py中覆写前提是已启用sphinx.ext.napoleon# conf.py extensions [sphinx.ext.napoleon] napoleon_google_docstring True # 解析 Google 风格 napoleon_numpy_docstring True # 解析 NumPy 风格 napoleon_include_init_with_doc False # 是否将 __init__ docstring 单独列出 napoleon_include_private_with_doc False # 是否收录带 docstring 的私有成员 napoleon_include_special_with_doc True # 是否收录带 docstring 的特殊成员 napoleon_use_admonition_for_examples False # Example/Examples 用 admonition 还是 rubric napoleon_use_admonition_for_notes False # Notes 用 admonition 还是 rubric napoleon_use_admonition_for_references False # References 用 admonition 还是 rubric napoleon_use_ivar False # 实例变量用 :ivar: 还是 .. attribute:: napoleon_use_param True # 参数用 :param: 还是单个 :parameters: napoleon_use_rtype True # 返回类型用 :rtype: 还是内联 napoleon_preprocess_types False # 是否将 docstring 内类型转为引用 napoleon_type_aliases None # 类型名到引用/别名的映射 napoleon_attr_annotations True # 是否使用 PEP 526 类属性注解各项语义与转换示例摘自 napoleon.rstnapoleon_include_init_with_doc True__init__的 docstring 作为独立条目列出False则沿用 Sphinx 默认行为并入类文档。注意没有 docstring 的__init__即使置 True 也不会收录。napoleon_use_admonition_for_examples/notes/references为True时相应节渲染为.. admonition::指令为False时渲染为.. rubric::。具体哪个更美观取决于 HTML 主题。单数Note节始终转换为.. note::指令不受该开关影响。napoleon_use_ivar True实例变量Attributes节转换为:ivar attr1:与:vartype attr1:角色False时转换为.. attribute:: attr1指令并在其下给出:type:。napoleon_use_param True每个参数生成独立的:param:/:type:行False时所有参数合并为单个:parameters:角色、以列表形式呈现。napoleon_use_keyword True与use_param类似但作用于关键字参数Keyword Args节生成独立的:keyword:角色渲染时作为独立的Keyword Arguments小节展示。napoleon_use_rtype True返回类型用:rtype:单独输出False时类型内联进:returns:描述如*bool* -- True if successful。napoleon_preprocess_types True自 3.2.1 起3.5 起对 Google 风格同样生效把 docstring 中的类型定义转换为引用。napoleon_type_aliases自 3.2 起仅当napoleon_use_param True时生效类型名到其他名称或引用的映射napoleon_type_aliases { CustomType: mypackage.CustomType, dict-like: :term:dict-like mapping, }例如Parameters节中的arg1 : CustomType会被转换为:type arg1: mypackage.CustomTypearg2 : dict-like会被转换为:type arg2: :term:dict-like 。napoleon_attr_annotations True自 3.4 起类体中的 PEP 526 注解作为属性的类型来源对应前述ExamplePEP526Class。napoleon_custom_sections自 1.8 起3.5 扩展定义自定义节。字符串条目表示通用节二元组(别名, 原节名)为已有节创建别名(节名, params_style | returns_style)则让自定义节按参数节或返回节样式渲染。源码层面的工作原理从源码看sphinx/ext/napoleon/docstring.pyGoogle 风格的解析由GoogleDocstring类完成其类 docstring 里直接给出了转换对照 from sphinx.ext.napoleon import Config config Config(napoleon_use_paramTrue, napoleon_use_rtypeTrue) docstring One line summary. ... ... Extended description. ... ... Args: ... arg1(int): Description of arg1 ... arg2(str): Description of arg2 ... Returns: ... str: Description of return value. ... print(GoogleDocstring(docstring, config)) One line summary. BLANKLINE Extended description. BLANKLINE :param arg1: Description of arg1 :type arg1: int :param arg2: Description of arg2 :type arg2: str BLANKLINE :returns: Description of return value. :rtype: str BLANKLINE可以推断其内部流程GoogleDocstring.__init__接收 docstring 文本与配置按行切分为队列后逐行扫描每遇到一个已注册的节标题大小写不敏感地查_sections字典就调用对应的_parse_*方法把节内容改写成 reStructuredText 字段:param:、:type:、:returns:、:rtype:、admonition 指令等。_sections字典把args、arguments、parameters统一指向_parse_parameters_section把yields指向_parse_yields_section把attention、warning等指向_parse_admonition——这正好解释了上一节别名与admonition 节为何成立。napoleon_custom_sections则通过_load_custom_sections在运行期向该字典追加条目。Napoleon 配置的默认值登记在 sphinx/ext/napoleon/init.py 的Config类中并通过add_config_value注册到 Sphinx 配置系统env域因此这些选项可以在构建过程中按环境生效也能被其它扩展读取。整个转换以预处理器形式挂在 autodoc 的 docstring 获取环节之前不改动磁盘上的源文件。如何在自己项目里复现这套写法在conf.py中启用 Napoleon见上文并按需覆写配置项用sphinx-apidoc -f -o docs/source projectdir生成 API 文档直接以 example_google.py 为模板模块级Attributes/Todo节、函数Args/Returns/Raises节、生成器Yields节、doctest 格式Examples节、类与__init__的文档分工、#:内联属性注释、getter 中写 property 文档运行python example_google.py可自行验证模块可导入、函数行为与 docstring 描述一致示例中module_level_function在param1 param2时确实抛出ValueError与 example_numpy.py 对照后选定一种风格全项目保持一致。按上述流程操作后autodoc 会把这些 docstring 渲染成带参数签名、类型链接、异常说明与示例的规范 API 页面同时你仍可在 docstring 中使用任意 reStructuredText 标记交叉引用、字面量块等实现可读源码 高质量文档两全。赞分享文档开发工具【免费下载链接】sphinxThe Sphinx documentation generator项目地址https://gitcode.com/gh_mirrors/sp/sphinx点击查看免费下载相关推荐Sphinx Napoleon 实战NumPy 风格 docstring 的规范书写与自动转换以 example_numpy 为例Sphinx Napoleon 实战NumPy 风格 docstring 的规范书写与自动转换以 example_numpy 为例 导读 本文以 Sphi文档开发工具Sphinx Napoleon 扩展全解析在 Sphinx 中优雅地使用 NumPy 与 Google 风格 docstringSphinx Napoleon 扩展全解析在 Sphinx 中优雅地使用 NumPy 与 Google 风格 docstring Sphinx 的 sphin文档开发工具NumPy Docstring 规范实战以 multivariate_normal 为例的完整写作指南NumPy Docstring 规范实战以 multivariate_normal 为例的完整写作指南 本文以 NumPy 仓库中的 doc/EXAMPLE_科学计算数据分析创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考