sphinx.ext.autodoc
-- docstringからのドキュメントの取り込み¶
この拡張機能は、docstringでドキュメントが書かれているモジュールをインポートして、そのdocstringから、半自動的にドキュメントを取り込みます。
警告
autodoc
imports the modules to be documented.
If any modules have side effects on import,
these will be executed by autodoc
when sphinx-build is run.
If you document scripts (as opposed to library modules),
make sure that the main routine is protected by
an if __name__ == '__main__'
condition.
For this to work, the docstrings must of course be written in correct reStructuredText. You can then use all of the usual Sphinx markup in the docstrings, and it will end up correctly in the documentation. Together with hand-written documentation, this technique eases the pain of having to maintain two locations for documentation, while at the same time avoiding auto-generated-looking pure API documentation.
If you prefer NumPy or Google style docstrings over reStructuredText,
you can also enable the napoleon
extension.
napoleon
is a preprocessor that converts docstrings
to correct reStructuredText before autodoc
processes them.
Getting started¶
Setup¶
Activate the plugin by adding 'sphinx.ext.autodoc'
to
the extensions
list in conf.py
:
extensions = [
...
'sphinx.ext.autodoc',
]
Ensuring the code can be imported¶
autodoc
analyses the code and docstrings
by introspection after importing the modules.
For importing to work, you have to make sure that your modules can be found
by Sphinx and that dependencies can be resolved
(if your module does import foo
, but foo
is not available
in the python environment that Sphinx runs in, your module import will fail).
There are two ways to ensure this:
Use an environment that contains your package and Sphinx. This can e.g. be your local development environment (with an editable install), or an environment in CI in which you install Sphinx and your package. The regular installation process ensures that your package can be found by Sphinx and that all dependencies are available.
It is alternatively possible to patch the Sphinx run so that it can operate directly on the sources; e.g. if you want to be able to do a Sphinx build from a source checkout.
Patch
sys.path
inconf.py
to include your source path. For example if you have a repository structure withdoc/conf.py
and your package is atsrc/my_package
, then you should add the following to yourconf.py
.import sys from pathlib import Path sys.path.insert(0, str(Path('..', 'src').resolve()))
To cope with missing dependencies, specify the missing modules in the
autodoc_mock_imports
setting.
使用方法¶
You can now use the ディレクティブ to add formatted documentation
for Python code elements like functions, classes, modules, etc.
For example, to document the function io.open()
,
reading its signature and docstring from the source file, you'd write:
.. autofunction:: io.open
You can also document whole classes or even modules automatically, using member options for the auto directives, like:
.. automodule:: io
:members:
Tip
As a hint to autodoc extension, you can put a ::
separator
between the module name and the object name
to let autodoc know the correct module, if it is ambiguous:
.. autoclass:: module.name::Noodle
Marking objects as public or private¶
autodoc considers a member private if its docstring contains
:meta private:
in its 詳細情報フィールドのリスト. For example:def my_function(my_arg, my_other_arg): """blah blah blah :meta private: """
Added in version 3.0.
autodoc considers a member public if its docstring contains
:meta public:
in its 詳細情報フィールドのリスト, even if it starts with an underscore. For example: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.
Doc comments and docstrings¶
Python has no built-in support for docstrings for
module data members or class attributes.
To allow documenting these, autodoc
recognises a special format of
comment called a 'doc comment' or 'documentation comment'.
These comments start with a colon and an optional space character,
'#:'
or '#: '
.
To be recognised, the comments must appear either on the same line
as the variable or on one or more lines before the variable.
Multi-line doc-comments must always appear on the lines before the
variable's definition.
For example, all three of the following variables have valid doc-comments:
egg_and_spam = 1.50 #: A simple meal
#: Spam! Lovely spam! Lovely spam!
egg_bacon_sausage_and_spam = 2.49
#: Truly gourmet cuisine for madam; Lobster Thermidor
#: aux Crevettes with a mornay sauce garnished with
#: truffle pate, brandy and a fried egg on top and spam.
lobster_thermidor = 35.00
Alternatively, autodoc
can recognise a docstring
on the line immediately following the definition.
In the the following class definition,
all attributes have documentation recognised by autodoc
:
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."""
ディレクティブ¶
autodoc
provides several directives that are versions of
the usual py:module
, py:class
and so forth.
On parsing time, they import the corresponding module
and extract the docstring of the given objects,
inserting them into the page source under a suitable
py:module
, py:class
etc. directive.
注釈
Just as py:class
respects the current
py:module
, autoclass
will also do so.
Likewise, automethod
will respect the current py:class
.
Default directive options¶
To make any of the options described below the default,
use the autodoc_default_options
dictionary in conf.py
.
If using defaults for the :members:
, :exclude-members:
,
:private-members:
, or :special-members:
options,
setting the option on a directive will override the default.
Instead, to extend the default list with the per-directive option,
the list may be prepended with a plus sign (+
),
as follows:
.. autoclass:: Noodle
:members: eat
:private-members: +_spicy, _garlickly
Tip
If using autodoc_default_options
,
the defaults can be disabled per-directive with the negated form,
:no-option:
as an option of the directive
For example:
.. automodule:: foo
:no-undoc-members:
Automatically document modules¶
- .. automodule::¶
Document a module. By default, the directive only inserts the docstring of the module itself:
.. automodule:: noodles
will produce source like this:
.. py:module:: noodles The noodles module.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring (but before any automatic member documentation).
Therefore, you can also mix automatic and non-automatic member documentation, as follows:
.. automodule:: noodles :members: Noodle .. py:function:: boiled_noodle(time=10) Create a noodle that has been boiled for *time* minutes.
オプション
- :no-index:¶
Do not generate an index entry for the documented module or any auto-documented members.
Added in version 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented module or any auto-documented members. Unlike
:no-index:
, cross-references are still created.Added in version 8.2.
- :platform: platforms (comma separated list)¶
Indicate platforms on which the module is available. This is identical to
py:module
's:platform:
option.
- :synopsis: purpose (text)¶
A sentence describing the module's purpose. This is identical to
py:module
's:synopsis:
option.Added in version 0.5.
- :deprecated:¶
Mark a module as deprecated. This is identical to
py:module
's:deprecated:
option.Added in version 0.5.
- :ignore-module-all: (no value)¶
Do not use
__all__
when analysing the module to document.Added in version 1.7.
Options for selecting members to document
- :members: (no value or comma separated list)¶
Generate automatic documentation for all members of the target module:
.. automodule:: noodles :members:
By default,
autodoc
only includes public members with a docstring or doc-comment (#:
). If__all__
exists, it will be used to define which members are public, unless the:ignore-module-all:
option is set.To only document certain members, an explicit comma-separated list may be used as the argument to
:members:
:.. automodule:: noodles :members: Noodle
- :exclude-members: (comma separated list)¶
Exclude the given names from the members to document. For example:
.. automodule:: noodles :members: :exclude-members: NoodleBase
Added in version 0.6.
- :imported-members: (no value)¶
To prevent documentation of imported classes or functions, in an
automodule
directive with themembers
option set, only module members where the__module__
attribute is equal to the module name given toautomodule
will be documented.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.
Added in version 1.2.
- :undoc-members:¶
Generate automatic documentation for members of the target module that don't have a docstring or doc-comment. For example:
.. automodule:: noodles :members: :undoc-members:
- :private-members: (no value or comma separated list)¶
Generate automatic documentation for private members of the target module. This includes names with a leading underscore (e.g.
_private
) and those members explicitly marked as private with:meta private:
... automodule:: noodles :members: :private-members:
To only document certain private members, an explicit comma-separated list may be used as the argument to
:private-members:
:.. automodule:: noodles :members: :private-members: _spicy, _garlickly
Added in version 1.1.
バージョン 3.2 で変更: The option can now take a comma-separated list of arguments.
- :special-members: (no value or comma separated list)¶
Generate automatic documentation for special members of the target module, also known as 'dunder' names. This includes all names enclosed with a double-underscore, e.g.
__special__
:.. automodule:: my.Class :members: :special-members:
To only document certain special members, an explicit comma-separated list may be used as the argument to
:special-members:
:.. automodule:: noodles :members: :special-members: __version__
Added in version 1.1.
バージョン 1.2 で変更: The option can now take a comma-separated list of arguments.
Options for documented members
- :member-order: (alphabetical, bysource, or groupwise)¶
Choose the ordering of automatically documented members (default:
alphabetical
). This overrides theautodoc_member_order
setting.alphabetical
: Use simple alphabetical order.groupwise
: Group by object type (class, function, etc), use alphabetical order within groups.bysource
: Use the order of objects in the module's source. The__all__
variable can be used to override this order.
ソースコードの定義順を指定する場合には、対象のモジュールはPythonモジュールで、ソースコードが利用できるようになっていなければなりません。
Added in version 0.6.
バージョン 1.0 で変更: Support the
'bysource'
option.
- :show-inheritance: (no value)¶
Enable the
:show-inheritance:
option for all members of the module, if:members:
is enabled.Added in version 0.4.
Automatically document classes or exceptions¶
- .. autoclass::¶
- .. autoexception::¶
Document a class. For exception classes, prefer
.. autoexception::
. By default, the directive only inserts the docstring of the class itself:.. autoclass:: noodles.Noodle
will produce source like this:
.. py:class:: Noodle The Noodle class's docstring.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring (but before any automatic member documentation).
Therefore, you can also mix automatic and non-automatic member documentation, as follows:
.. autoclass:: noodles.Noodle :members: eat, slurp .. py:method:: boil(time=10) Boil the noodle for *time* minutes.
Advanced usage
It is 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:: noodles.Noodle(type) .. automethod:: eat(persona)
この機能はデコレータなどによって、メソッドの呼び出し規約が内省機能で取れない状態になっている場合に便利です。
Added in version 0.4.
オプション
- :no-index:¶
Do not generate an index entry for the documented class or any auto-documented members.
Added in version 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented class or any auto-documented members. Unlike
:no-index:
, cross-references are still created.Added in version 8.2.
- :class-doc-from: (class, init, or both)¶
Select which docstring will be used for the main body of the directive. This overrides the global value of
autoclass_content
. The possible values are:class
: Only use the class's docstring. The__init__()
method can be separately documented using the:members:
option orautomethod
.init
: Only use the docstring of the__init__()
method.both
: Use both, appending the docstring of the__init__()
method to the class's docstring.
If the
__init__()
method doesn't exist or has a blank docstring,autodoc
will attempt to use the__new__()
method's docstring, if it exists and is not blank.Added in version 4.1.
Options for selecting members to document
- :members: (no value or comma separated list)¶
Generate automatic documentation for all members of the target class:
.. autoclass:: noodles.Noodle :members:
By default,
autodoc
only includes public members with a docstring or doc-comment (#:
) that are attributes of the target class (i.e. not inherited).To only document certain members, an explicit comma-separated list may be used as the argument to
:members:
:.. autoclass:: noodles.Noodle :members: eat, slurp
- :exclude-members: (comma separated list)¶
Exclude the given names from the members to document. For example:
.. autoclass:: noodles.Noodle :members: :exclude-members: prepare
Added in version 0.6.
- :inherited-members: (comma separated list)¶
To generate automatic documentation for members inherited from base classes, use the
:inherited-members:
option:.. autoclass:: noodles.Noodle :members: :inherited-members:
This can be combined with the
:undoc-members:
option to generate automatic documentation for all available members of the class.The members of classes listed in the argument to
:inherited-members:
are excluded from the automatic documentation. This defaults toobject
if no argument is provided, meaning that members of theobject
class are not documented. To include these, useNone
as the argument.For example; If your class
MyList
is derived fromlist
class and you don't want to documentlist.__len__()
, you should specify a option:inherited-members: list
to avoid special members of list class.注釈
Should any of the inherited members use a format other than reStructuredText for their docstrings, there may be markup warnings or errors.
Added in version 0.3.
バージョン 3.0 で変更:
:inherited-members:
now takes the name of a base class to exclude as an argument.バージョン 5.0 で変更: A comma separated list of base class names can be used.
- :undoc-members: (no value)¶
Generate automatic documentation for members of the target class that don't have a docstring or doc-comment. For example:
.. autoclass:: noodles.Noodle :members: :undoc-members:
- :private-members: (no value or comma separated list)¶
Generate automatic documentation for private members of the target class. This includes names with a leading underscore (e.g.
_private
) and those members explicitly marked as private with:meta private:
... autoclass:: noodles.Noodle :members: :private-members:
To only document certain private members, an explicit comma-separated list may be used as the argument to
:private-members:
:.. autoclass:: noodles.Noodle :members: :private-members: _spicy, _garlickly
Added in version 1.1.
バージョン 3.2 で変更: The option can now take arguments.
- :special-members: (no value or comma separated list)¶
Generate automatic documentation for special members of the target class, also known as 'dunder' names. This includes all names enclosed with a double-underscore, e.g.
__special__
:.. autoclass:: noodles.Noodle :members: :special-members:
To only document certain special members, an explicit comma-separated list may be used as the argument to
:special-members:
:.. autoclass:: noodles.Noodle :members: :special-members: __init__, __name__
Added in version 1.1.
バージョン 1.2 で変更: The option can now take a comma-separated list of arguments.
Options for documented members
- :member-order: (alphabetical, bysource, or groupwise)¶
Choose the ordering of automatically documented members (default:
alphabetical
). This overrides theautodoc_member_order
setting.'alphabetical'
: Use simple alphabetical order.'groupwise'
: Group by object type (class, function, etc), use alphabetical order within groups.'bysource'
: Use the order of objects in the module's source. The__all__
variable can be used to override this order.
ソースコードの定義順を指定する場合には、対象のモジュールはPythonモジュールで、ソースコードが利用できるようになっていなければなりません。
Added in version 0.6.
バージョン 1.0 で変更: Support the
'bysource'
option.
- :show-inheritance: (no value)¶
Insert the class's base classes after the class signature.
Added in version 0.4.
Automatically document function-like objects¶
- .. autofunction::¶
- .. automethod::¶
- .. autoproperty::¶
- .. autodecorator::¶
Document a function, method, property, or decorator. By default, the directive only inserts the docstring of the function itself:
.. autofunction:: noodles.average_noodle
will produce source like this:
.. py:function:: noodles.average_noodle The average_noodle function's docstring.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring.
Therefore, you can also mix automatic and non-automatic documentation, as follows:
.. autofunction:: noodles.average_noodle .. note:: For more flexibility, use the :py:class:`!Noodle` class.
Added in version 2.0:
autodecorator
.Added in version 2.1:
autoproperty
.注釈
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.Advanced usage
It is 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)
この機能はデコレータなどによって、メソッドの呼び出し規約が内省機能で取れない状態になっている場合に便利です。
Added in version 0.4.
オプション
- :no-index:¶
Do not generate an index entry for the documented function.
Added in version 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented function. Unlike
:no-index:
, cross-references are still created.Added in version 8.2.
Automatically document attributes or data¶
- .. autodata::¶
- .. autoattribute::¶
Document a module level variable or constant ('data') or class attribute. By default, the directive only inserts the docstring of the variable itself:
.. autodata:: noodles.FLOUR_TYPE
will produce source like this:
.. py:data:: noodles.FLOUR_TYPE The FLOUR_TYPE constant's docstring.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring.
Therefore, you can also mix automatic and non-automatic member documentation, as follows:
.. autodata:: noodles.FLOUR_TYPE .. hint:: Cooking time can vary by which flour type is used.
バージョン 0.6 で変更:
autodata
とautoattribute
がdocstringにも対応しました。バージョン 1.1 で変更: Doc-comments are now allowed on the same line of an assignment.
オプション
- :no-index:¶
Do not generate an index entry for the documented variable or constant.
Added in version 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented variable or constant. Unlike
:no-index:
, cross-references are still created.Added in version 8.2.
- :annotation: value (string)¶
Added in version 1.2.
By default,
autodoc
attempts to obtain the type annotation and value of the variable by introspection, displaying it after the variable's name. To override this, a custom string for the variable's value may be used as the argument toannotation
.For example, if the runtime value of
FILE_MODE
is0o755
, the displayed value will be493
(asoct(493) == '0o755'
). This can be fixed by setting:annotation: = 0o755
.If
:annotation:
is used without arguments, no value or type hint will be shown for the variable.
- :no-value:¶
Added in version 3.4.
To display the type hint of the variable without a value, use the
:no-value:
option. If both the:annotation:
and:no-value:
options are used,:no-value:
has no effect.
設定¶
There are also config values that you can set:
- autoclass_content¶
- Type:
str
- Default:
'class'
この値を指定することで、本体の
autoclass
ディレクティブにどの内容を追加するのかを選択できます。指定可能な値は以下の通りです:'class'
Only the class' docstring is inserted. You can still document
__init__
as a separate method usingautomethod
or themembers
option toautoclass
.'both'
クラスのdocstringと、
__init__
メソッドのdocstringの両方が結合されて挿入されます。'init'
__init__
メソッドのdocstringだけが挿入されます。
Added in version 0.3.
クラス内に
__init__
メソッドが定義されていない、または__init__
メソッドのドックストリングが空で__new__
メソッドにドックストリングが記述されている場合は、__new__
メソッドのドックストリングが代わりに使用されます。Added in version 1.4.
- autodoc_class_signature¶
- Type:
str
- Default:
'mixed'
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.
Added in version 4.1.
- autodoc_member_order¶
- Type:
str
- Default:
'alphabetical'
Define the order in which
automodule
andautoclass
members are listed. Supported values are:'alphabetical'
: Use alphabetical order.'groupwise'
: order by member type. The order is:for modules, exceptions, classes, functions, data
- for classes: class methods, static methods, methods,
and properties/attributes
Members are ordered alphabetically within groups.
'bysource'
: Use the order in which the members appear in the source code. This requires that the module must be a Python module with the source code available.
Added in version 0.6.
バージョン 1.0 で変更:
'bysource'
をサポートしました。
- autodoc_default_options¶
- Type:
dict[str, str | bool]
- Default:
{}
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
orTrue
to the value is equivalent to giving only the option name to the directives.The supported options are:
'members'
: Seeautomodule:members
.'undoc-members'
Seeautomodule:undoc-members
.'private-members'
: Seeautomodule:private-members
.'special-members'
: Seeautomodule:special-members
.'inherited-members'
: Seeautoclass:inherited-members
.'imported-members'
: Seeautomodule:imported-members
.'exclude-members'
: Seeautomodule:exclude-members
.'ignore-module-all'
: Seeautomodule:ignore-module-all
.'member-order'
: Seeautomodule:member-order
.'show-inheritance'
: Seeautoclass:show-inheritance
.'class-doc-from'
: Seeautoclass:class-doc-from
.'no-value'
: Seeautodata:no-value
.'no-index'
: Seeautomodule:no-index
.'no-index-entry'
: Seeautomodule:no-index-entry
.
Added in version 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¶
- Type:
bool
- Default:
True
Cモジュールからインポートされた関数は、情報を取得できないため、これらの関数に関するシグニチャを自動的に決定することはできません。しかし、これを使用すると、これらの関数のdocstringの最初の行に、これらの関数のシグニチャを入れられます。
もしこの設定を
True
(デフォルト)にすると、autodocは関数やメソッドのdocstringの最初の行を見て、もしシグニチャのような情報が書かれていたら、その行をシグニチャとして読み込み、docstringからはその行の内容を削除して扱います。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 で変更: Support overloaded signatures
バージョン 4.0 で変更: Overloaded signatures do not need to be separated by a backslash
- autodoc_mock_imports¶
- Type:
list[str]
- Default:
[]
この値はモックアップされるモジュールのリストを含みます。これはビルド時もしくはビルド過程の中断時にいくつかの外部依存が満たされない時に有用です。依存関係自体のルートパッケージのみを指定し、サブモジュールを省略できます:
autodoc_mock_imports = ['django']
Will mock all imports under the
django
package.Added in version 1.3.
バージョン 1.6 で変更: この設定値は、モックされるべきトップレベルモジュールを宣言するためだけに必要です。
- autodoc_typehints¶
- Type:
str
- Default:
'signature'
This value controls how to represent typehints. The setting takes the following values:
'signature'
-- Show typehints in the signature'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.
Added in version 2.1.
Added in version 3.0: New option
'description'
is added.Added in version 4.1: New option
'both'
is added.
- autodoc_typehints_description_target¶
- Type:
str
- Default:
'all'
This value controls whether the types of undocumented parameters and return values are documented when
autodoc_typehints
is set to'description'
. Supported values:'all'
: Types are documented for all parameters and return values, whether they are documented or not.'documented'
: Types will only be documented for a parameter or a return value that is already documented by the docstring.'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 isNone
).
Added in version 4.0.
Added in version 5.0: New option
'documented_params'
is added.
- autodoc_type_aliases¶
- Type:
dict[str, str]
- Default:
{}
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.
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¶
- Type:
str
- Default:
'short'
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 (e.g.io.StringIO
->StringIO
)
Added in version 4.4.
バージョン 5.0 で変更: The default setting was changed to
'short'
- autodoc_preserve_defaults¶
- Type:
bool
- Default:
False
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_use_type_comments¶
- Type:
bool
- Default:
True
Attempt to read
# type: ...
comments from source code to supplement missing type annotations, if True.This can be disabled if your source code does not use type comments, for example if it exclusively uses type annotations or does not use type hints of any kind.
Added in version 8.2: Added the option to disable the use of type comments in via the new
autodoc_use_type_comments
option, which defaults toTrue
for backwards compatibility. The default will change toFalse
in Sphinx 10.
- autodoc_warningiserror¶
- Type:
bool
- Default:
True
This value controls the behavior of
sphinx-build --fail-on-warning
during importing modules. IfFalse
is given, autodoc forcedly suppresses the error if the imported module emits warnings.バージョン 8.1 で変更: This option now has no effect as
--fail-on-warning
no longer exits early.
- autodoc_inherit_docstrings¶
- Type:
bool
- Default:
True
This value controls the docstrings inheritance. If set to True the docstring for classes or methods, if not explicitly set, is inherited from parents.
Added in version 1.7.
- suppress_warnings
- Type:
Sequence[str]
- Default:
()
autodoc
supports suppressing warning messages viasuppress_warnings
. It defines the following additional warnings types:autodoc
autodoc.import_object
Docstringのプリプロセス¶
autodocは以下のイベントを追加で提供します:
- autodoc-process-docstring(app, what, name, obj, options, lines)¶
Added in version 0.4.
autodocがdocstringを読み込んで処理をするタイミングで呼び出されます。linesは処理されたdocstringが入っている、文字列のリストです。このリストはイベントハンドラの中で変更でき、この結果を利用します。
- パラメータ:
app -- Sphinxのアプリケーションオブジェクト
what -- the type of the object which the docstring belongs to (one of
'module'
,'class'
,'exception'
,'function'
,'method'
,'attribute'
)name -- オブジェクトの完全な修飾付きの名前
obj -- オブジェクト自身
options -- the options given to the directive: an object with attributes
inherited_members
,undoc_members
,show_inheritance
andno-index
that are true if the flag option of same name was given to the auto directivelines -- docstringの行数。上記を参照。
- autodoc-before-process-signature(app, obj, bound_method)¶
Added in version 2.4.
Emitted before autodoc formats a signature for an object. The event handler can modify an object to change its signature.
- パラメータ:
app -- Sphinxのアプリケーションオブジェクト
obj -- オブジェクト自身
bound_method -- a boolean indicates an object is bound method or not
- autodoc-process-signature(app, what, name, obj, options, signature, return_annotation)¶
Added in version 0.5.
autodocがオブジェクトのシグニチャをフォーマットしているときに呼び出されます。イベントハンドラは新しいタプル
(signature, return_annotation)
を返すことができ、Sphinxはこの出力を使ってドキュメントを生成します。- パラメータ:
app -- Sphinxのアプリケーションオブジェクト
what -- the type of the object which the docstring belongs to (one of
'module'
,'class'
,'exception'
,'function'
,'method'
,'attribute'
)name -- オブジェクトの完全な修飾付きの名前
obj -- オブジェクト自身
options -- the options given to the directive: an object with attributes
inherited_members
,undoc_members
,show_inheritance
andno-index
that are true if the flag option of same name was given to the auto directivesignature -- function signature, as a string of the form
'(parameter_1, parameter_2)'
, orNone
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'
, orNone
if there is no return annotation
sphinx.ext.autodoc
モジュールではautodoc-process-docstring
イベント内でdocstringを処理する上で一般的に必要とされるようなファクトリー関数をいくつか提供しています:
- sphinx.ext.autodoc.cut_lines(pre: int, post: int = 0, what: Sequence[str] | None = None) _AutodocProcessDocstringListener [ソース]¶
全てのdocstringの最初の pre 行と、最後の post 行を削除するリスナーを返します。 what として文字列の配列が渡されると、この what に含まれているタイプのdocstringだけが処理されます。
この関数は
conf.py
の中のsetup()
などで、以下のように使用します。from sphinx.ext.autodoc import cut_lines app.connect('autodoc-process-docstring', cut_lines(4, what={'module'}))
これは
automodule_skip_lines
の代わりに使用できます (そしてそうすべきです)。
- sphinx.ext.autodoc.between(marker: str, what: Sequence[str] | None = None, keepempty: bool = False, exclude: bool = False) _AutodocProcessDocstringListener [ソース]¶
marker の正規表現にマッチしている行の間だけを保持する、または exclude がtrueならば除外する、リスナーを返します。もしも一行もマッチしない場合には、docstringが空になる可能性がありますが、 keepempty がtrueでない場合には、変更されません。
もしも what として、文字列の配列が渡されると、この what に含まれているタイプのdocstringだけが処理されます。
- 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 reStructuredText.
メンバーのスキップ¶
autodocでは以下のイベントを発行することで、指定されたメンバーをドキュメントに含めるかどうかをユーザが決定できるようになっています:
- autodoc-skip-member(app, what, name, obj, skip, options)¶
Added in version 0.5.
autodocがメンバーをドキュメントに含めるかどうかを決定するときに呼ばれます。もしもこのハンドラーが
True
を返すとメンバーのドキュメントは外されます。False
を返すと含まれるようになります。複数の有効な拡張モジュールが
autodoc-skip-member
イベントを処理する場合、autodocはハンドラが返す最初の非None
値を使用します。ハンドラは、autodocおよびその他の有効な拡張モジュールのスキップ動作に戻るには、None
を返す必要があります。- パラメータ:
app -- Sphinxのアプリケーションオブジェクト
what -- the type of the object which the docstring belongs to (one of
'module'
,'class'
,'exception'
,'function'
,'method'
,'attribute'
)name -- オブジェクトの完全な修飾付きの名前
obj -- オブジェクト自身
skip -- ユーザーハンドラーが上書きしない場合に、autodocがこのメンバーを飛ばすかどうかの真偽値。
options -- the options given to the directive: an object with attributes
inherited_members
,undoc_members
,show_inheritance
andno-index
that are true if the flag option of same name was given to the auto directive