:模式:sphinx.ext.autodoc–包括来自docstrings的文档

这个插件可以导入正在编写文档的模块,并以半自动的方式从文档字符串中拉入文档。

备注

为了让Sphinx(实际上是执行Sphinx的Python解释器)找到您的模块,它必须是可导入的。这意味着模块或包必须位于以下目录之一:data:搜索路径–调整您的:数据:`搜索路径`在相应的配置文件中。

警告

autodocimport 所有需要自动生成文档的模块。如果某些模块在导入时有一些额外的操作,在运行 sphinx-build 时,也会被 autodoc 执行。

如果你要引入脚本(而不是库模块),确保主程序 main 有这个条件保护着:if __name__ == '__main__'

为了实现这一点,文档字符串当然必须用正确的重构文本编写。然后您可以在文档字符串中使用所有通常的Sphinx标记,它将在文档中正确结束。与手工编写的文档一起,这种技术减轻了为文档维护两个位置的负担,同时避免了自动生成的纯API文档。

如果您喜欢“NumPy”或“Google”样式的文档字符串而不是重构文本,还可以启用:mod:napoleon <sphinx.ext.napoleon>。:mod:`napoleon<sphinx.ext.napoleon>`是一个预处理器,它在mod:`autodoc`处理文档字符串之前将其转换为正确的重构文本。

指令

:mod:autodoc`提供了几种常见指令的版本:rst:方向:`py:module,:rst:方向:py:class`等等。解析时,它们导入相应的模块并提取给定对象的docstring,将它们插入到页面源代码中的适当位置:rst:方向:`py:module,:rst:方向:`py:class:etc.指令。

备注

就像:rst:方向:py:class`尊重当前:rst:方向:`py:module,:rst:方向:autoclass`也会这样做。同样地:rst:方向:`automethod`将尊重当前:rst:方向:`py:class

.. automodule::
.. autoclass::
.. autoexception::

记录模块、类或异常。默认情况下,这三个指令都只插入对象本身的文档字符串::

.. autoclass:: Noodle

会产生这样的来源:

.. class:: Noodle

   Noodle's docstring.

“auto”指令也可以包含自己的内容,它将被插入到文档字符串之后(但在任何自动成员文档之前)生成的非auto指令源中。

因此,您还可以混合使用自动和非自动成员文档,例如:

.. autoclass:: Noodle
   :members: eat, slurp

   .. method:: boil(time=10)

      Boil the noodle *time* minutes.

选项

:members: (no value or comma separated list)

If set, autodoc will generate document for the members of the target module, class or exception.

例如:

.. automodule:: noodle
   :members:

将记录所有模块成员(递归),并且:

.. autoclass:: Noodle
   :members:

will document all class member methods and properties.

By default, autodoc will not generate document for the members that are private, not having docstrings, inherited from super class, or special members.

对于模块,在查找成员时,除非提供“ignore module all”标志选项,否则在查找成员时将考虑使用“ignore module all”标志选项。如果没有`ignore module all``,成员的顺序也将是`uuu all_uu2;`中的顺序。

您也可以给出一个明确的成员列表;只有这些成员才会被记录下来:

.. autoclass:: Noodle
   :members: eat, slurp
:undoc-members: (no value)

If set, autodoc will also generate document for the members not having docstrings:

.. automodule:: noodle
   :members:
   :undoc-members:
:private-members: (no value or comma separated list)

If set, autodoc will also generate document for the private members (that is, those named like _private or __private):

.. automodule:: noodle
   :members:
   :private-members:

它还可以采用一个显式的成员名称列表作为参数进行记录:

.. automodule:: noodle
   :members:
   :private-members: _spicy, _garlickly

Added in version 1.1.

在 3.2 版本发生变更: 选项现在可以接受参数。

:special-members: (no value or comma separated list)

If set, autodoc will also generate document for the special members (that is, those named like __special__):

.. autoclass:: my.Class
   :members:
   :special-members:

它还可以采用一个显式的成员名称列表作为参数进行记录:

.. autoclass:: my.Class
   :members:
   :special-members: __init__, __name__

Added in version 1.1.

在 1.2 版本发生变更: The option can now take arguments

选项和高级用法

  • 如果要将“成员”选项(或下面描述的其他选项)设为默认选项,请参阅:confval:autodoc_default_options

    小技巧

    您可以使用一个否定形式:samp:’no-{flag}’,作为autodoc指令的一个选项,暂时禁用它。例如::

    .. automodule:: foo
       :no-undoc-members:
    

    小技巧

    You can use autodoc directive options to temporarily override or extend default options which takes list as an input. For example:

    .. autoclass:: Noodle
       :members: eat
       :private-members: +_spicy, _garlickly
    

    在 3.5 版本发生变更: The default options can be overridden or extended temporarily.

  • 如果某个成员的docstring在其:ref:info field list`中包含“:meta private:`”,则autodoc将其视为私有成员。例如:

    def my_function(my_arg, my_other_arg):
        """blah blah blah
    
        :meta private:
        """
    

    Added in version 3.0.

  • 如果某个成员的docstring在其:ref:info field list`中包含“:meta public:``”,即使它以下划线开头,它也会认为它是公共的。例如:

    def _my_function(my_arg, my_other_arg):
        """blah blah blah
    
        :meta public:
        """
    

    Added in version 3.1.

  • autodoc considers a variable member does not have any default value if its docstring contains :meta hide-value: in its 信息字段列表. Example:

    var1 = None  #: :meta hide-value:
    

    Added in version 3.5.

  • 对于类和异常,在记录所有成员时,从基类继承的成员将被忽略,除非除了“members”之外,还提供了“inherited members”选项:

    .. autoclass:: Noodle
       :members:
       :inherited-members:
    

    这可以与“非文档成员”结合使用,以记录类或模块的*所有*可用成员。

    它可以使用一个祖先类而不记录从它继承的成员。默认情况下,不记录“object”类的成员。要显示它们,请给选项“None”。

    例如,如果您的类“Foo”是从“list”类派生而来的,并且您不想记录“list.uu len_uuu9()”,则应指定一个选项“:inherited members:list”,以避免列表类的特殊成员。

    如果你的另一个特殊的’uuuu’和’uuu’方法都是特殊的’uuu’成员,但你的另一个特殊的’uuu’成员将被记录为另一个特殊的’uuu`成员,而你的另一个’uuu’方法将被记录为一个特殊的’uuu`成员,而你的另一个’uuuu’成员将被记录为一个特殊的’u``u`成员,而你的’uu’和’u``u都被特殊的’。

    Since v5.0, it can take a comma separated list of ancestor classes. It allows to suppress inherited members of several classes on the module at once by specifying the option to automodule directive.

    注意:如果继承成员来自文档字符串不是reST格式的模块,这将导致标记错误。

    Added in version 0.3.

    在 3.0 版本发生变更: It takes an ancestor class name as an argument.

    在 5.0 版本发生变更: It takes a comma separated list of ancestor class names.

  • 可以使用常规语法覆盖显式记录的可调用对象(函数、方法、类)的签名,该语法将覆盖从自省获得的签名:

    .. autoclass:: Noodle(type)
    
       .. automethod:: eat(persona)
    

    如果方法的签名被修饰符隐藏,这很有用。

    Added in version 0.4.

  • 这个:rst:方向:自动模块’,:rst:方向:`自动类`和:rst:方向:`自动例外`指令还支持名为“展示继承”的标志选项。当给定时,基类列表将插入类签名的正下方(与:rst:方向:`自动模块,这将为模块中记录的每个类插入)。

    Added in version 0.4.

  • All autodoc directives support the no-index flag option that has the same effect as for standard py:function etc. directives: no index entries are generated for the documented object (and all autodocumented members).

    Added in version 0.4.

  • :rst:方向:`自动模块`还识别标准的“概要”、“平台”和“已弃用”选项:rst:方向:`py:模块`指令支持。

    Added in version 0.5.

  • :rst:方向:`自动模块`和:rst:方向:`自动类’还有一个“成员顺序r”选项,可用于重写一个指令的全局值:confval:`自动文档_成员_顺序’。

    Added in version 0.6.

  • 支持成员文档的指令还有一个“排除成员”选项,如果要记录所有成员,可以使用该选项从文档中排除单个成员名称。

    Added in version 0.6.

  • 在一个:rst:方向:`自动模块`指令在设置了``成语啊``选项的情况下,只会记录其``eu 模块`u``属性等于给`自动模块`的模块名的模块成员。这是为了防止记录导入的类或函数。如果要阻止此行为并记录所有可用成员,请设置“导入成员”选项。请注意,导入模块中的属性不会被记录,因为属性文档是通过解析当前模块的源文件发现的。

    Added in version 1.2.

  • 在:confval:`自动文档_模拟_导入`中添加模块列表,以防止在生成时某些外部依赖项不可导入时发生导入错误,从而停止生成过程。

    Added in version 1.3.

  • 作为对autodoc扩展的提示,您可以在模块名和对象名之间放置一个“::”分隔符,以便在模块名不明确时让autodoc知道正确的模块名。:

    .. autoclass:: module.name::Noodle
    
  • autoclass also recognizes the class-doc-from option that can be used to override the global value of autoclass_content.

    Added in version 4.1.

.. autofunction::
.. autodecorator::
.. autodata::
.. automethod::
.. autoattribute::
.. autoproperty::

它们的工作原理与:rst:方向:`自动类`等,但不提供用于自动成员文档的选项。

:rst:方向:`autodata`和:rst:方向:`autoattribute`支持`annotation``选项。该选项控制变量值的显示方式。如果不带参数指定,则只打印变量的名称,并且不显示其值:

.. autodata:: CD_DRIVE
   :annotation:

如果使用参数指定选项,则将其作为变量的值打印在名称之后:

.. autodata:: CD_DRIVE
   :annotation: = your CD device name

默认情况下,如果没有“annotation”选项,Sphinx会尝试获取变量的值并将其打印在名称之后。

The no-value option can be used instead of a blank annotation to show the type hint but not the value:

.. autodata:: CD_DRIVE
   :no-value:

If both the annotation and no-value options are used, no-value has no effect.

对于模块数据成员和类属性,可以将文档放入具有特殊格式的注释中(使用`#:来启动注释,而不仅仅是`#`),也可以放在定义之后的文档字符串*。注释必须在定义前*的行上,或者在赋值*后的同一行*。后一种形式仅限于一行。

这意味着在下面的类定义中,可以自动记录所有属性:

class Foo:
    """Docstring for class Foo."""

    #: Doc comment for class attribute Foo.bar.
    #: It can have multiple lines.
    bar = 1

    flox = 1.5   #: Doc comment for Foo.flox. One line only.

    baz = 2
    """Docstring for class attribute Foo.baz."""

    def __init__(self):
        #: Doc comment for instance attribute qux.
        self.qux = 3

        self.spam = 4
        """Docstring for instance attribute spam."""

在 0.6 版本发生变更: :rst:方向:`自动数据`和:rst:方向:`自动属性`现在可以提取文档字符串。

在 1.1 版本发生变更: 现在允许在赋值后的同一行上添加注释文档。

在 1.2 版本发生变更: 引用:自动数据`和引用有``自动注解``选项的`自动属性

在 2.0 版本发生变更: autodecorator 已添加.

在 2.1 版本发生变更: autoproperty added.

在 3.4 版本发生变更: autodata and autoattribute now have a no-value option.

备注

如果您记录修饰过的函数或方法,请记住,autodoc通过导入模块并检查给定函数或方法的“`uuu 文档_uu2;”属性来检索其文档字符串。这意味着,如果一个装饰器用另一个函数替换装饰函数,它必须将原来的“uuu文档_uu2;”复制到新函数中。

配置

您还可以设置配置值:

autoclass_content

此值选择将插入到主体的内容:rst:方向:`自动类`指令。可能的值为:

"类"

只插入类的文档字符串。这是默认值。您仍然可以使用以下方法将“uuu 初始_u2;”作为单独的方法进行文档记录:rst:方向:`自动方法`或``成语那``选项用于:rst:方向:`自动类

"都"

类和方法的文档字符串都被连接并插入。

"初始化"

只插入方法的文档字符串。

Added in version 0.3.

如果类没有```unu 初始``方法,或者如果```u 初始_u``方法的文档字符串为空,但该类有一个```unu 新`方法的文档字符串,则改用它。

Added in version 1.4.

autodoc_class_signature

This value selects how the signature will be displayed for the class defined by autoclass directive. The possible values are:

"mixed"

Display the signature with the class name.

"separated"

Display the signature as a method.

The default is "mixed".

Added in version 4.1.

autodoc_member_order

此值选择自动记录的成员是按字母顺序排序(值为“字母”),是按成员类型(值为“集团化”)还是按源顺序排序(值为“按源”)。默认值为字母顺序。

请注意,对于源代码顺序,该模块必须是具有可用源代码的Python模块。

Added in version 0.6.

在 1.0 版本发生变更: 支持“bysource”。

autodoc_default_flags

此值是自动应用于所有autodoc指令的autodoc指令标志的列表。受支持的标志是“’members’”、“’undoc-members’”、“’private-members’”、“’special-members’”、“’inherited-members’”、“’show-inheritation’”、“’ignore-module-all”和“exclude-members”`

Added in version 1.0.

自 1.8 版本弃用: 集成到:confval:autodoc_default_options

autodoc_default_options

autodoc指令的默认选项。它们将自动应用于所有autodoc指令。它必须是将选项名称映射到值的字典。例如::

autodoc_default_options = {
    'members': 'var1, var2',
    'member-order': 'bysource',
    'special-members': '__init__',
    'undoc-members': True,
    'exclude-members': '__weakref__'
}

将“None”或“True”设置为值相当于只给指令指定选项名。

The supported options are 'members', 'member-order', 'undoc-members', 'private-members', 'special-members', 'inherited-members', 'show-inheritance', 'ignore-module-all', 'imported-members', 'exclude-members', 'class-doc-from' and 'no-value'.

Added in version 1.8.

在 2.0 版本发生变更: 接受“True”作为值。

在 2.1 版本发生变更: 添加 'imported-members'.

在 4.1 版本发生变更: Added 'class-doc-from'.

在 4.5 版本发生变更: Added 'no-value'.

autodoc_docstring_signature

从C模块导入的函数不能自省,因此不能自动确定这些函数的签名。但是,将签名放入函数的文档字符串的第一行是一个常用的约定。

如果此布尔值设置为“True”(默认值),自动文档将查看文档字符串的第一行以查找函数和方法,如果它看起来像签名,则使用该行作为签名,并将其从文档字符串内容中删除。

autodoc will continue to look for multiple signature lines, stopping at the first line that does not look like a signature. This is useful for declaring overloaded function signatures.

Added in version 1.1.

在 3.1 版本发生变更: 支持重载签名

在 4.0 版本发生变更: Overloaded signatures do not need to be separated by a backslash

autodoc_mock_imports

此值包含要模拟的模块列表。当某些外部依赖项在构建时不满足并中断构建过程时,这很有用。只能指定依赖项本身的根包,而忽略子模块:

autodoc_mock_imports = ["django"]

将模拟“django”包下的所有导入。

Added in version 1.3.

在 1.6 版本发生变更: 这个配置值只需要声明应该模拟的顶层模块。

autodoc_typehints

This value controls how to represent typehints. The setting takes the following values:

  • 'signature' – Show typehints in the signature (default)

  • 'description' – Show typehints as content of the function or method The typehints of overloaded functions or methods will still be represented in the signature.

  • ``’none’`–不显示类型提示

  • 'both' – Show typehints in the signature and as content of the function or method

Overloaded functions or methods will not have typehints included in the description because it is impossible to accurately represent all possible overloads as a list of parameters.

Added in version 2.1.

Added in version 3.0: 添加了新选项“description”。

Added in version 4.1: New option 'both' is added.

autodoc_typehints_description_target

This value controls whether the types of undocumented parameters and return values are documented when autodoc_typehints is set to description.

The default value is "all", meaning that types are documented for all parameters and return values, whether they are documented or not.

When set to "documented", types will only be documented for a parameter or a return value that is already documented by the docstring.

With "documented_params", parameter types will only be annotated if the parameter is documented in the docstring. The return type is always annotated (except if it is None).

Added in version 4.0.

Added in version 5.0: New option 'documented_params' is added.

autodoc_type_aliases

A dictionary for users defined type aliases that maps a type name to the full-qualified object name. It is used to keep type aliases not evaluated in the document. Defaults to empty ({}).

The type aliases are only available if your program enables Postponed Evaluation of Annotations (PEP 563) feature via from __future__ import annotations.

For example, there is code using a type alias:

from __future__ import annotations

AliasType = Union[List[Dict[Tuple[int, str], Set[int]]], Tuple[str, List[str]]]

def f() -> AliasType:
    ...

If autodoc_type_aliases is not set, autodoc will generate internal mark-up from this code as following:

.. py:function:: f() -> Union[List[Dict[Tuple[int, str], Set[int]]], Tuple[str, List[str]]]

   ...

If you set autodoc_type_aliases as {'AliasType': 'your.module.AliasType'}, it generates the following document internally:

.. py:function:: f() -> your.module.AliasType:

   ...

Added in version 3.3.

autodoc_typehints_format

This value controls the format of typehints. The setting takes the following values:

  • 'fully-qualified' – Show the module name and its name of typehints

  • 'short' – Suppress the leading module names of the typehints (ex. io.StringIO -> StringIO) (default)

Added in version 4.4.

在 5.0 版本发生变更: The default setting was changed to 'short'

autodoc_preserve_defaults

If True, the default argument values of functions will be not evaluated on generating document. It preserves them as is in the source code.

Added in version 4.0: Added as an experimental feature. This will be integrated into autodoc core in the future.

autodoc_warningiserror

此值控制导入模块期间:option:`sphinx build-W`的行为。如果给定了“False”,则如果导入的模块发出警告,autodoc将强制取消该错误。默认为“True”。

autodoc_inherit_docstrings

此值控制docstrings继承。如果设置为True,则类或方法的docstring(如果未显式设置)将从父级继承。

默认值为真。

Added in version 1.7.

suppress_warnings

:mod:`autodoc`支持通过:confval:`suppress_warnings`来取消警告消息。它还允许以下警告类型:

  • autodoc

  • autodoc.import_object

文档字符串预处理

自动文档提供如下额外事件

autodoc-process-docstring(app, what, name, obj, options, lines)

Added in version 0.4.

当自动文档读取并处理文档字符串时发出。*lines*是一个字符串列表,即已处理的文档字符串的行,事件处理程序可以修改**就地**以更改Sphinx在输出中的内容。

参数:
  • app – sphinx应用目标

  • what – 文档字符串所属对象的类型(“模块”、“类”、“异常”、“函数”、“方法”、“属性”之一)

  • name – 对象的完全限定名

  • obj – 对象自身

  • options – the options given to the directive: an object with attributes inherited_members, undoc_members, show_inheritance and no-index that are true if the flag option of same name was given to the auto directive

  • lines – 文档字符串的行,见上文

autodoc-before-process-signature(app, obj, bound_method)

Added in version 2.4.

在autodoc格式化对象的签名之前发出。事件处理程序可以修改对象以更改其签名。

参数:
  • app – sphinx应用目标

  • obj – 对象自身

  • bound_method – 布尔值表示对象是否是绑定方法

autodoc-process-signature(app, what, name, obj, options, signature, return_annotation)

Added in version 0.5.

当自动文档已格式化对象的签名时发出。事件处理程序可以返回一个新的元组`(签名,返回标记)``来更改Sphinx在输出中的内容。

参数:
  • app – sphinx应用目标

  • what – 文档字符串所属对象的类型(“模块”、“类”、“异常”、“函数”、“方法”、“属性”之一)

  • name – 对象的完全限定名

  • obj – 对象自身

  • options – the options given to the directive: an object with attributes inherited_members, undoc_members, show_inheritance and no-index that are true if the flag option of same name was given to the auto directive

  • signature – 函数签名,如果自省未成功,并且指令中未指定签名,则为格式为“`”(参数_1,参数_2)”``或“无”形式的字符串。

  • return_annotation – 函数return annotation,格式为“—>annotation”`,如果没有return annotation,则返回“None”

:mod:sphinx.ext.autodoc`模块提供工厂函数,用于在事件:事件:`自动文档处理文档字符串:

sphinx.ext.autodoc.cut_lines(pre: int, post: int = 0, what: str | None = None) Callable[源代码]

返回一个侦听器,它删除每个文档字符串的第一行*pre*行和最后一行*post*。如果*what*是字符串序列,则只处理*what*中类型的文档字符串。

像这样使用(例如在file:file的``setup()``函数中:配置文件):

from sphinx.ext.autodoc import cut_lines
app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))

这可以(也应该)代替:confval:automodule_skip_lines

sphinx.ext.autodoc.between(marker: str, what: Sequence[str] | None = None, keepempty: bool = False, exclude: bool = False) Callable[源代码]

返回一个侦听器,该侦听器保留或如果*exclude*为真,则排除与*marker*正则表达式匹配的行之间的行。如果没有行匹配,则生成的文档字符串将为空,因此除非*keepmpty*为真,否则不会进行任何更改。

如果*what*是字符串序列,则只处理*what*中类型的文档字符串。

autodoc-process-bases(app, name, obj, options, bases)

Emitted when autodoc has read and processed a class to determine the base-classes. bases is a list of classes that the event handler can modify in place to change what Sphinx puts into the output. It’s emitted only if show-inheritance option given.

参数:
  • app – sphinx应用目标

  • name – 对象的完全限定名

  • obj – 对象自身

  • options – the options given to the class directive

  • bases – the list of base classes signature. see above.

Added in version 4.1.

在 4.3 版本发生变更: bases can contain a string as a base class name. It will be processed as reST mark-up’ed text.

跳过成员

自动文档允许用户定义一个自定义方法,通过使用以下事件确定是否应将成员包括在文档中:

autodoc-skip-member(app, what, name, obj, skip, options)

Added in version 0.5.

当自动文档必须决定是否应将成员包含在文档中时发出。如果处理程序返回“True”,则排除该成员。如果处理程序返回“False”,则会包含此函数。

如果多个已启用的扩展处理“自动文档跳过成员r”事件,自动文档将使用处理程序返回的第一个非“None”值。处理程序应返回“None”以返回自动文档和其他已启用扩展的跳过行为。

参数:
  • app – sphinx应用目标

  • what – 文档字符串所属对象的类型(“模块”、“类”、“异常”、“函数”、“方法”、“属性”之一)

  • name – 对象的完全限定名

  • obj – 对象自身

  • skip – 一个布尔值,指示如果用户处理程序不重写决策,自动文档是否将跳过此成员

  • options – the options given to the directive: an object with attributes inherited_members, undoc_members, show_inheritance and no-index that are true if the flag option of same name was given to the auto directive