sphinx.ext.autodoc —— 包括来自文档字符串的文档

这个插件可以导入你正在记录的模块,并以半自动的方式从文档字符串提取文档。

备注

为了让 Sphinx(实际上是执行 Sphinx 的 Python 解释器)找到你的模块,它必须是可导入的。这意味着模块或包必须在 sys.path 上的一个目录中 —— 在配置文件中相应地调整 sys.path

警告

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

如果你记录了脚本(相对于库模块而言),请确保它们的主程序受到 if __name__ == '__main__' 条件的保护。

为了使其发挥作用,文档字符串当然必须用正确的 reStructuredText 写。然后你可以在文档字符串中使用所有常规的 Sphinx 标记,它最终会正确地出现在文档中。再加上手写的文档,这种技术减轻了必须维护两个位置的文档的痛苦,同时也避免了自动生成的纯 API 文档。

如果你喜欢 NumPyGoogle 风格的文档字符串而不是 reStructuredText,你也可以启用 napoleon 插件。napoleon 是一个预处理器,在 autodoc 处理之前将文档字符串转换为正确的 reStructuredText。

指令

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

备注

就像 py:class 遵从当前 py:module 一样,autoclass 也会这样做。同样地,automethod 也会遵从当前的 py:class

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

记录一个模块、类或异常。所有这三个指令默认只插入对象本身的文档字符串

.. autoclass:: Noodle

将产生这样的源码

.. class:: Noodle

   Noodle's docstring.

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

因此,你也可以把自动和非自动的成员文件混在一起,像这样

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

   .. method:: boil(time=10)

      Boil the noodle *time* minutes.

选项

:members: (no value or comma separated list)

如果设置,autodoc 将为目标模块、类或异常的成员生成文档。

例如

.. automodule:: noodle
   :members:

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

.. autoclass:: Noodle
   :members:

将记录所有的类成员方法和属性。

默认情况下,autodoc 不会为那些私有的、没有文档字符串的、从超类继承的、或特殊的成员生成文档。

对于模块,在寻找成员时,__all__ 将被遵从,除非你给出 ignore-module-all 标志选项。如果没有 ignore-module-all,成员的顺序也将是 __all__ 中的顺序。

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

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

It can also take an explicit list of member names to be documented as arguments:

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

1.1 新版功能.

在 3.2 版更改: The option can now take arguments.

: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:

It can also take an explicit list of member names to be documented as arguments:

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

1.1 新版功能.

在 1.2 版更改: The option can now take arguments

Options and advanced usage

  • If you want to make the members option (or other options described below) the default, see autodoc_default_options.

    小技巧

    You can use a negated form, 'no-flag', as an option of autodoc directive, to disable it temporarily. For example:

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

  • autodoc considers a member private if its docstring contains :meta private: in its Info field lists. For example:

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

    3.0 新版功能.

  • autodoc considers a member public if its docstring contains :meta public: in its Info field lists, even if it starts with an underscore. For example:

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

    3.1 新版功能.

  • autodoc considers a variable member does not have any default value if its docstring contains :meta hide-value: in its Info field lists. Example:

    var1 = None  #: :meta hide-value:
    

    3.5 新版功能.

  • For classes and exceptions, members inherited from base classes will be left out when documenting all members, unless you give the inherited-members 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.

    It can take an ancestor class not to document inherited members from it. By default, members of object class are not documented. To show them all, give None to the option.

    For example; If your class Foo is derived from list class and you don’t want to document list.__len__(), you should specify a option :inherited-members: list to avoid special members of list class.

    Another example; If your class Foo has __str__ special method and autodoc directive has both inherited-members and special-members, __str__ will be documented as in the past, but other special method that are not implemented in your class Foo.

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

    0.3 新版功能.

    在 3.0 版更改: It takes an ancestor class name as an argument.

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

  • As a hint to autodoc extension, you can put a :: separator in between module name and object name to let autodoc know the correct module name if it is ambiguous.

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

    4.1 新版功能.

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

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

autodata and autoattribute support the annotation option. The option controls how the value of variable is shown. If specified without arguments, only the name of the variable will be printed, and its value is not shown:

.. autodata:: CD_DRIVE
   :annotation:

If the option specified with arguments, it is printed after the name as a value of the variable:

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

By default, without annotation option, Sphinx tries to obtain the value of the variable and print it after the name.

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.

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.

在 2.1 版更改: autoproperty added.

在 3.4 版更改: autodata and autoattribute now have a no-value option.

备注

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.

Configuration

There are also config values that you can set:

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_class_signature

This value selects how the signautre 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".

4.1 新版功能.

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 版更改: Support for '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', 'imported-members', 'exclude-members', 'class-doc-from' and 'no-value'.

1.8 新版功能.

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

在 2.1 版更改: Added 'imported-members'.

在 4.1 版更改: Added 'class-doc-from'.

在 4.5 版更改: Added 'no-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.

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.

1.1 新版功能.

在 3.1 版更改: Support overloaded signatures

在 4.0 版更改: Overloaded signatures do not need to be separated by a backslash

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_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' – Do not show typehints

  • '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.

2.1 新版功能.

3.0 新版功能: New option 'description' is added.

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.

4.0 新版功能.

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:

   ...

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 (default)

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

4.4 新版功能.

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.

4.0 新版功能: Added as an experimental feature. This will be integrated into autodoc core in the future.

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 from 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 preprocessing

autodoc provides the following additional events:

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 – the Sphinx application object

  • what – the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute")

  • name – the fully qualified name of the object

  • obj – the object itself

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

  • lines – the lines of the docstring, see above

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

2.4 新版功能.

Emitted before autodoc formats a signature for an object. The event handler can modify an object to change its signature.

Parameters
  • app – the Sphinx application object

  • obj – the object itself

  • bound_method – a boolean indicates an object is bound method or not

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

0.5 新版功能.

Emitted when autodoc has formatted a signature for an object. The event handler can return a new tuple (signature, return_annotation) to change what Sphinx puts into the output.

Parameters
  • app – the Sphinx application object

  • what – the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute")

  • name – the fully qualified name of the object

  • obj – the object itself

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

  • 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: Optional[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: Optional[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-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.

Parameters
  • app – the Sphinx application object

  • name – the fully qualified name of the object

  • obj – the object itself

  • options – the options given to the class directive

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

4.1 新版功能.

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

Skipping members

autodoc allows the user to define a custom method for determining whether a member should be included in the documentation by using the following event:

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

0.5 新版功能.

Emitted when autodoc has to decide whether a member should be included in the documentation. The member is excluded if a handler returns True. It is included if the handler returns False.

If more than one enabled extension handles the autodoc-skip-member event, autodoc will use the first non-None value returned by a handler. Handlers should return None to fall back to the skipping behavior of autodoc and other enabled extensions.

Parameters
  • app – the Sphinx application object

  • what – the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute")

  • name – the fully qualified name of the object

  • obj – the object itself

  • skip – a boolean indicating if autodoc will skip this member if the user handler does not override the decision

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