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

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

## 指令¶

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

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

.. 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."""


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 新版功能.

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 新版功能.

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 新版功能.

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.

Parameters
• 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放入输出的内容。

Parameters
• 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: int, post: int = 0, what: str = None) → Callable[源代码]

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: str, what: Sequence[str] = None, keepempty: bool = False, exclude: bool = False) → Callable[源代码]

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 ，则包含它。

Parameters
• app – Sphinx应用程序对象

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

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

• obj – 对象本身

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

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