sphinx.ext.autodoc -- docstringからのドキュメントの取り込み

この拡張機能は、docstringでドキュメントが書かれているモジュールをインポートして、そのdocstringから、半自動的にドキュメントを取り込みます。

注釈

Sphinx(実際にはSphinxを実行しているPythonインタプリタ)がモジュールを見つけるためには、そのモジュールはインポート可能になっていなければなりません。これは、インポートしたいモジュールやパッケージがsys.pathで設定されているディレクトリのどれかに入っている必要があるということです。設定ファイル内で、適宜sys.pathを調整してください。

警告

autodoc はドキュメンテーションされるモジュールを インポート します. もしインポートによる副作用があれば、 sphinx-build が実行されるとき autodoc により実行されます。

もしあなたが (ライブラリモジュールではなく) スクリプトをドキュメント化したいのであれば、スクリプトのメインルーチンが if __name__ == '__main__' 条件により保護されていることを確認して下さい。

この機能をうまく働かせるためには、docstringは正しいreStructuredTextのフォーマットに従って記述されている必要があります。また、すべてのSphinxのマークアップをdocstringの中に書くことができ、最終的に正しくドキュメンテーションされます。手書きのドキュメントと一緒にモジュールのドキュメントを作成する場合には、純粋なAPIのドキュメントを同時に自動生成できるため、この機能を使うことで両方を同時に管理する苦痛が軽減されます。

If you prefer NumPy or Google style docstrings over reStructuredText, you can also enable the napoleon extension. napoleon is a preprocessor that converts your docstrings to correct reStructuredText before autodoc processes them.

ディレクティブ

autodoc は通常のpy:module, py:classなどのディレクティブに似た別バージョンのディレクティブを提供します。ドキュメントのパース時に指定されたモジュールを読み込んで、docstringを抽出して、その内容を通常のpy:module, py:classディレクティブと一緒に差込みます。

注釈

py:classを宣言したときに、既に定義されているpy:moduleの中に配置されるのと同様に、autoclassも同じように振舞います。automethodpy:classについても同様です。

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

モジュール、クラス、例外のドキュメントを作成します。これらのディレクティブは、デフォルトでは指定されたオブジェクトのdocstringだけを読み込みます:

.. autoclass:: Noodle

これを実行すると以下のようなreSTのソースコードが生成されます:

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

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 フラグオプションを指定しない限り、メンバーを探すのに __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

オプション/進んだ使い方

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

    Tip

    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:
    

    Tip

    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 詳細情報フィールドのリスト. 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 詳細情報フィールドのリスト, 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 詳細情報フィールドのリスト. 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:
    

    このフラグとundoc-membersを同時に適用すると、クラスとモジュールの持っている、すべての利用可能なメンバーのドキュメントが作成されるようになります。

    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.

    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.

    注意: もしもdocstringがreST形式でないモジュールで定義されたメンバーがあると、マークアップエラーになるでしょう。

    バージョン 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)
    

    この機能はデコレータなどによって、メソッドの呼び出し規約が内省機能で取れない状態になっている場合に便利です。

    バージョン 0.4 で追加.

  • automoduleと、autoclassautoexceptionディレクティブはshow-inheritanceというオプションをサポートしています。これが設定されると、クラスのシグニチャの直前に、継承しているベースクラスのリストが表示されるようになります。automoduleに対して使用すると、モジュール内でドキュメントが記述されているすべてのクラスのベースクラスが表示されるようになります。

    バージョン 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).

    バージョン 0.4 で追加.

  • automoduleは標準のpy:moduleディレクティブがサポートしているsynopsis, platform, deprecatedオプションをサポートしています。

    バージョン 0.5 で追加.

  • automoduleautoclassmember-orderというオプションを持っています。これを設定すると、このディレクティブの中でのみグローバルなautodoc_member_orderという設定をオーバーライドできます。

    バージョン 0.6 で追加.

  • メンバーのドキュメント生成をサポートしているディレクティブはexclude-membersというオプションも持っています。これはすべてのドキュメントを生成する場合に、除外したいメンバーの名前をひとつだけ追加するのに使用します。

    バージョン 0.6 で追加.

  • membersオプションが設定されているautomoduleディレクティブの中では、__module__属性がautomoduleで与えられたモジュール名と等しいメンバーのみのドキュメントが生成されます。これはインポートされたクラスや関数のドキュメントまで生成しないための措置です。 imported-members オプションによって、この動作をさせないよう指定でき、全てのメンバーをドキュメント化します。インポートしたモジュールの属性はドキュメント化されないことに注意してください。これは、属性のドキュメント化は現在のモジュールのソースコードをパースして行うためです。

    バージョン 1.2 で追加.

  • ビルド時に依存モジュールがインポートできない場合に、 ビルド処理を終了するインポートエラーを防止する為に autodoc_mock_imports 内のモジュールリストを追加します。

    バージョン 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::

これらのディレクティブはautoclassなどと同じように動作しますが、メンバー内のドキュメント生成のオプションはありません。

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.

モジュールのデータメンバーとクラス属性については、特別なフォーマットでコメントの中に (コメントの開始に単に # を使う代わりに #: を使用して)、または定義の 後の docstring の中にドキュメンテーションを入れることができます。コメントは、定義の 前の それ自身の行、または代入の直後の 同じ行に 置く必要があります。後者の形式は1行のみに制限されます。

これが意味するのは、次のクラス定義ですべての属性が autodocument 化できるということです:

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 で変更: autodataautoattribute がdocstringにも対応しました。

バージョン 1.1 で変更: 代入文の直後にコメントドキュメントを書けるようになりました。

バージョン 1.2 で変更: autodataautoattributeannotation オプションがあります。

バージョン 2.0 で変更: autodecorator added.

バージョン 2.1 で変更: autoproperty added.

バージョン 3.4 で変更: autodata and autoattribute now have a no-value option.

注釈

もしもデコレータのついた関数やメソッドのドキュメントを生成する場合には、autodocが、実際にモジュールをインポートして、指定された関数やメソッドの__doc__属性を見てドキュメントを生成しているということに注意してください。これは、もしデコレートされた関数が他のものに置き換えられる場合には、元の__doc__の内容を新しい関数にもコピーしなければ動作しないということを意味しています。

設定

There are also config values that you can set:

autoclass_content

この値を指定することで、本体のautoclassディレクティブにどの内容を追加するのかを選択できます。指定可能な値は以下の通りです:

"class"

クラスのdocstringだけが挿入されます。これがデフォルトの動作になります。automethodを使用するか、autoclassに対してmembersオプションを設定することで、__init__の内容は別のメソッドとしてドキュメント化できます。

"both"

クラスのdocstringと、__init__メソッドのdocstringの両方が結合されて挿入されます。

"init"

__init__メソッドのdocstringだけが挿入されます。

バージョン 0.3 で追加.

クラス内に __init__ メソッドが定義されていない、または __init__ メソッドのドックストリングが空で __new__ メソッドにドックストリングが記述されている場合は、 __new__ メソッドのドックストリングが代わりに使用されます。

バージョン 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".

バージョン 4.1 で追加.

autodoc_member_order

これの設定を変更することで、ドキュメントのついたメンバーをアルファベット順にソートするか('alphabetical')、もしくはメンバーのタイプによって('groupwise')ソートするか、ソースコードの定義順('bysource')にソートするかを変更できます。デフォルトはアルファベット順です。

ソースコードの定義順を指定する場合には、対象のモジュールはPythonモジュールで、ソースコードが利用できるようになっていなければなりません。

バージョン 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', '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

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.

バージョン 1.1 で追加.

バージョン 3.1 で変更: Support overloaded signatures

バージョン 4.0 で変更: Overloaded signatures do not need to be separated by a backslash

autodoc_mock_imports

この値はモックアップされるモジュールのリストを含みます。これはビルド時もしくはビルド過程の中断時にいくつかの外部依存が満たされない時に有用です。依存関係自体のルートパッケージのみを指定し、サブモジュールを省略できます:

autodoc_mock_imports = ["django"]

Will mock all imports under the django package.

バージョン 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' -- 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.

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

バージョン 4.0 で追加.

バージョン 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:

   ...

バージョン 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)

バージョン 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.

バージョン 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.

デフォルト値は 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 で追加.

autodocがdocstringを読み込んで処理をするタイミングで呼び出されます。linesは処理されたdocstringが入っている、文字列のリストです。このリストはイベントハンドラの中で変更でき、この結果を利用します。

パラメータ:
  • app -- Sphinxのアプリケーションオブジェクト

  • what -- docstringが属するオブジェクトの型 (以下のうちのどれか "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 and no-index that are true if the flag option of same name was given to the auto directive

  • lines -- docstringの行数。上記を参照。

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.

パラメータ:
  • 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)

バージョン 0.5 で追加.

autodocがオブジェクトのシグニチャをフォーマットしているときに呼び出されます。イベントハンドラは新しいタプル(signature, return_annotation)を返すことができ、Sphinxはこの出力を使ってドキュメントを生成します。

パラメータ:
  • app -- Sphinxのアプリケーションオブジェクト

  • what -- docstringが属するオブジェクトの型 (以下のうちのどれか "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 and no-index that are true if the flag option of same name was given to the auto directive

  • signature -- "(parameter_1, parameter_2)" という形式の文字列で示される関数シグニチャか、あるいは、イントロスペクションが成功せず、シグニチャをディレクティブ中で特定できない場合には None となります。

  • return_annotation -- アノテーションを " -> annotation" という形式の文字列で返す関数か、アノテーションを返さない場合は None となります。

sphinx.ext.autodocモジュールではautodoc-process-docstringイベント内でdocstringを処理する上で一般的に必要とされるようなファクトリー関数をいくつか提供しています:

sphinx.ext.autodoc.cut_lines(pre: int, post: int = 0, what: str | None = None) Callable[ソース]

全ての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) Callable[ソース]

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.

バージョン 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では以下のイベントを発行することで、指定されたメンバーをドキュメントに含めるかどうかをユーザが決定できるようになっています:

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

バージョン 0.5 で追加.

autodocがメンバーをドキュメントに含めるかどうかを決定するときに呼ばれます。もしもこのハンドラーがTrueを返すとメンバーのドキュメントは外されます。Falseを返すと含まれるようになります。

複数の有効な拡張モジュールが autodoc-skip-member イベントを処理する場合、autodocはハンドラが返す最初の非 None 値を使用します。ハンドラは、autodocおよびその他の有効な拡張モジュールのスキップ動作に戻るには、 None を返す必要があります。

パラメータ:
  • app -- Sphinxのアプリケーションオブジェクト

  • what -- docstringが属するオブジェクトの型 (以下のうちのどれか "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 and no-index that are true if the flag option of same name was given to the auto directive