sphinx.ext.autodoc – 包括docstrings中的文档

此扩展可以导入您正在记录的模块,并以半自动方式从文档字符串中提取文档。

注解

对于Sphinx(实际上是执行Sphinx的Python解释器)来查找模块,它必须是可导入的。 这意味着模块或包必须位于以下目录之一 sys.path - 相应地调整配置文件中的 sys.path

警告

autodoc 导入 要记录的模块。如果任何模块对导入有副作用,那么当运行 sphinx-build 时,这些将由 autodoc 执行。

如果您记录脚本(而不是库模块),请确保它们的主例程受 if __name__ == '__main__' 条件的保护。

为了实现这一点,文档字符串当然必须用正确的reStructuredText编写。然后,您可以在文档字符串中使用所有常用的Sphinx标记,它最终会在文档中正确显示。与手写文档一起,这种技术减轻了必须维护两个文档位置的痛苦,同时避免了自动生成的纯API文档。

如果您更喜欢 NumPyGoogle 样式文档字符串而不是 reStructuredText,您还可以启用 napoleon 扩展名。 napoleon 是一个预处理器,可以将你的文档字符串转换为正确的reStructuredText autodoc 处理它们。

指令

autodoc 提供了几个通常版本的指令 py:modulepy:class 等等。在解析时,他们导入相应的模块并提取给定对象的文档字符串,将它们插入适当的页面源 py:modulepy:class 等。指示。

注解

就像 py:class 尊重当前 py:moduleautoclass 也会这样做。同样地, automethod 将尊重当前 py:class

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

记录模块,类或异常。 默认情况下,所有三个指令都只插入对象本身的docstring:

.. autoclass:: Noodle

会产生这样的来源:

.. class:: Noodle

   Noodle's docstring.

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

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

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

   .. method:: boil(time=10)

      Boil the noodle *time* minutes.

选项和高级用法

  • 如果你想自动记录成员,那就有一个 members 选项:

    .. automodule:: noodle
       :members:
    

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

    .. autoclass:: Noodle
       :members:
    

    将记录所有非私有成员函数和属性(即名称不以 _ 开头的那些)。

    对于模块,除非你给出 ignore-module-all 标志选项,否则在查找成员时将会尊重 __all__ 。没有 ignore-module-all ,成员的顺序也将是 __all__ 中的顺序。

    您还可以提供明确的成员列表;只有这些将被记录:

    .. autoclass:: Noodle
       :members: eat, slurp
    
  • 如果你想使 members 选项(或下面描述的其他选项)成为默认选项,请参阅 autodoc_default_options

    小技巧

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

    .. automodule:: foo
       :no-undoc-members:
    
  • 没有docstrings的成员将被省略,除非你给出``undoc-members`` 标志选项:

    .. automodule:: noodle
       :members:
       :undoc-members:
    
  • 如果给出 private-members flag选项,将包含 Private 成员(即名为 _private__private 的成员)。

    1.1 新版功能.

  • Python “special” members (that is, those named like __special__) will be included if the special-members flag option is given:

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

    would document both “private” and “special” members of the class.

    1.1 新版功能.

    在 1.2 版更改: The option can now take arguments, i.e. the special members to document.

  • For classes and exceptions, members inherited from base classes will be left out when documenting all members, unless you give the inherited-members flag option, in addition to members:

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

    This can be combined with undoc-members to document all available members of the class or module.

    Note: this will lead to markup errors if the inherited members come from a module whose docstrings are not reST formatted.

    0.3 新版功能.

  • It’s possible to override the signature for explicitly documented callable objects (functions, methods, classes) with the regular syntax that will override the signature gained from introspection:

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

    This is useful if the signature from the method is hidden by a decorator.

    0.4 新版功能.

  • The automodule, autoclass and autoexception directives also support a flag option called show-inheritance. When given, a list of base classes will be inserted just below the class signature (when used with automodule, this will be inserted for every class that is documented in the module).

    0.4 新版功能.

  • All autodoc directives support the noindex 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).

    0.4 新版功能.

  • automodule also recognizes the synopsis, platform and deprecated options that the standard py:module directive supports.

    0.5 新版功能.

  • automodule and autoclass also has an member-order option that can be used to override the global value of autodoc_member_order for one directive.

    0.6 新版功能.

  • The directives supporting member documentation also have a exclude-members option that can be used to exclude single member names from documentation, if all members are to be documented.

    0.6 新版功能.

  • In an automodule directive with the members option set, only module members whose __module__ attribute is equal to the module name as given to automodule will be documented. This is to prevent documentation of imported classes or functions. Set the imported-members option if you want to prevent this behavior and document all available members. Note that attributes from imported modules will not be documented, because attribute documentation is discovered by parsing the source file of the current module.

    1.2 新版功能.

  • Add a list of modules in the autodoc_mock_imports to prevent import errors to halt the building process when some external dependencies are not importable at build time.

    1.3 新版功能.

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

These work exactly like autoclass etc., but do not offer the options used for automatic member documentation.

autodata and autoattribute support the annotation option. Without this option, the representation of the object will be shown in the documentation. When the option is given without arguments, only the name of the object will be printed:

.. autodata:: CD_DRIVE
   :annotation:

You can tell sphinx what should be printed after the name:

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

For module data members and class attributes, documentation can either be put into a comment with special formatting (using a #: to start the comment instead of just #), or in a docstring after the definition. Comments need to be either on a line of their own before the definition, or immediately after the assignment on the same line. The latter form is restricted to one line only.

This means that in the following class definition, all attributes can be autodocumented:

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 版更改: autodata and autoattribute can now extract docstrings.

在 1.1 版更改: Comment docs are now allowed on the same line after an assignment.

在 1.2 版更改: autodata and autoattribute have an annotation option.

在 2.0 版更改: autodecorator added.

注解

If you document decorated functions or methods, keep in mind that autodoc retrieves its docstrings by importing the module and inspecting the __doc__ attribute of the given function or method. That means that if a decorator replaces the decorated function with another, it must copy the original __doc__ to the new function.

From Python 2.5, functools.wraps() can be used to create well-behaved decorating functions.

配置

您还可以设置配置值:

autoclass_content

This value selects what content will be inserted into the main body of an autoclass directive. The possible values are:

"class"

Only the class’ docstring is inserted. This is the default. You can still document __init__ as a separate method using automethod or the members option to autoclass.

"both"

Both the class’ and the __init__ method’s docstring are concatenated and inserted.

"init"

Only the __init__ method’s docstring is inserted.

0.3 新版功能.

If the class has no __init__ method or if the __init__ method’s docstring is empty, but the class has a __new__ method’s docstring, it is used instead.

1.4 新版功能.

autodoc_member_order

This value selects if automatically documented members are sorted alphabetical (value 'alphabetical'), by member type (value 'groupwise') or by source order (value 'bysource'). The default is alphabetical.

Note that for source order, the module must be a Python module with the source code available.

0.6 新版功能.

在 1.0 版更改: 支持 'bysource'.

autodoc_default_flags

This value is a list of autodoc directive flags that should be automatically applied to all autodoc directives. The supported flags are 'members', 'undoc-members', 'private-members', 'special-members', 'inherited-members', 'show-inheritance', 'ignore-module-all' and 'exclude-members'.

1.0 新版功能.

1.8 版后已移除: Integrated into autodoc_default_options.

autodoc_default_options

The default options for autodoc directives. They are applied to all autodoc directives automatically. It must be a dictionary which maps option names to the values. For example:

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

Setting None or True to the value is equivalent to giving only the option name to the directives.

The supported options are 'members', 'member-order', 'undoc-members', 'private-members', 'special-members', 'inherited-members', 'show-inheritance', 'ignore-module-all' and 'exclude-members'.

1.8 新版功能.

在 2.0 版更改: Accepts True as a value.

autodoc_docstring_signature

Functions imported from C modules cannot be introspected, and therefore the signature for such functions cannot be automatically determined. However, it is an often-used convention to put the signature into the first line of the function’s docstring.

If this boolean value is set to True (which is the default), autodoc will look at the first line of the docstring for functions and methods, and if it looks like a signature, use the line as the signature and remove it from the docstring content.

1.1 新版功能.

autodoc_mock_imports

This value contains a list of modules to be mocked up. This is useful when some external dependencies are not met at build time and break the building process. You may only specify the root package of the dependencies themselves and omit the sub-modules:

autodoc_mock_imports = ["django"]

Will mock all imports under the django package.

1.3 新版功能.

在 1.6 版更改: This config value only requires to declare the top-level modules that should be mocked.

autodoc_warningiserror

This value controls the behavior of sphinx-build -W during importing modules. If False is given, autodoc forcedly suppresses the error if the imported module emits warnings. By default, True.

autodoc_inherit_docstrings

This value controls the docstrings inheritance. If set to True the docstring for classes or methods, if not explicitly set, is inherited form parents.

The default is True.

1.7 新版功能.

suppress_warnings

autodoc supports to suppress warning messages via suppress_warnings. It allows following warnings types in addition:

  • autodoc

  • autodoc.import_object

Docstring预处理

autodoc提供以下附加事件:

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

0.4 新版功能.

Emitted when autodoc has read and processed a docstring. lines is a list of strings – the lines of the processed docstring – that the event handler can modify in place to change what Sphinx puts into the output.

参数
  • app – Sphinx应用程序对象

  • what – docstring属于它的对象的类型 (之一 "module", "class", "exception", "function", "method", "attribute")

  • name – 对象的完全限定名称

  • obj – 对象本身

  • options – 指令的选项:具有属性 inherited_membersundoc_membersshow_inheritancenoindex 的对象,如果为auto指令赋予了相同名称的flag选项,则为 true

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

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

0.5 新版功能.

autodoc格式化对象的签名时发出。事件处理程序可以返回一个新的元组 (signature, return_annotation) 来改变Sphinx放入输出的内容。

参数
  • app – Sphinx应用程序对象

  • what – docstring属于它的对象的类型 (之一 "module", "class", "exception", "function", "method", "attribute")

  • name – 对象的完全限定名称

  • obj – 对象本身

  • options – 指令的选项:具有属性 inherited_membersundoc_membersshow_inheritancenoindex 的对象,如果为auto指令赋予了相同名称的flag选项,则为 true

  • signature – function signature, as a string of the form "(parameter_1, parameter_2)", or None if introspection didn’t succeed and signature wasn’t specified in the directive.

  • return_annotation – function return annotation as a string of the form " -> annotation", or None if there is no return annotation

The sphinx.ext.autodoc module provides factory functions for commonly needed docstring processing in event autodoc-process-docstring:

sphinx.ext.autodoc.cut_lines(pre, post=0, what=None)[源代码]

Return a listener that removes the first pre and last post lines of every docstring. If what is a sequence of strings, only docstrings of a type in what will be processed.

Use like this (e.g. in the setup() function of conf.py):

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

This can (and should) be used in place of automodule_skip_lines.

sphinx.ext.autodoc.between(marker, what=None, keepempty=False, exclude=False)[源代码]

Return a listener that either keeps, or if exclude is True excludes, lines between lines that match the marker regular expression. If no line matches, the resulting docstring would be empty, so no change will be made unless keepempty is true.

If what is a sequence of strings, only docstrings of a type in what will be processed.

跳过会员

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

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

0.5 新版功能.

autodoc必须决定是否应将成员包含在文档中时发出。如果处理程序返回 True,则排除该成员。如果处理程序返回 False ,则包含它。

如果多个启用的扩展处理 autodoc-skip-member 事件,autodoc将使用处理程序返回的第一个 non-None 值。处理程序应返回 None 以回退到autodoc和其他已启用扩展的跳过行为。

参数
  • app – Sphinx应用程序对象

  • what – docstring属于它的对象的类型 (之一 "module", "class", "exception", "function", "method", "attribute")

  • name – 对象的完全限定名称

  • obj – 对象本身

  • skip – 一个布尔值,指示如果用户处理程序未覆盖该决定,autodoc是否将跳过此成员

  • options – 指令的选项:具有属性 inherited_membersundoc_membersshow_inheritancenoindex 的对象,如果为auto指令赋予了相同名称的flag选项,则为 true