Debian Codegraph @

doc/usage/extensions/autodoc.rst

raw
1 .. _ext-autodoc:
2
3 :mod:`sphinx.ext.autodoc` -- Include documentation from docstrings
4 ==================================================================
5
6 .. py:module:: sphinx.ext.autodoc
7 :synopsis: Include documentation from docstrings.
8
9 .. index:: pair: automatic; documentation
10 single: docstring
11
12 .. role:: code-py(code)
13 :language: Python
14
15 This extension can import the modules you are documenting,
16 and pull in documentation from docstrings in a semi-automatic way.
17
18 .. warning::
19
20 :mod:`~sphinx.ext.autodoc` **imports** the modules to be documented.
21 If any modules have side effects on import,
22 these will be executed by ``autodoc`` when :program:`sphinx-build` is run.
23
24 If you document scripts (as opposed to library modules),
25 make sure that the main routine is protected by
26 an ``if __name__ == '__main__'`` condition.
27
28 For this to work, the docstrings must of course be written in correct
29 reStructuredText.
30 You can then use all of the usual Sphinx markup in the docstrings,
31 and it will end up correctly in the documentation.
32 Together with hand-written documentation, this technique eases
33 the pain of having to maintain two locations for documentation,
34 while at the same time avoiding auto-generated-looking pure API documentation.
35
36 If you prefer `NumPy`_ or `Google`_ style docstrings over reStructuredText,
37 you can also enable the :mod:`napoleon <sphinx.ext.napoleon>` extension.
38 :mod:`!napoleon` is a preprocessor that converts docstrings
39 to correct reStructuredText before ``autodoc`` processes them.
40
41 .. _Google: https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings
42 .. _NumPy: https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard
43
44
45 Getting started
46 ---------------
47
48
49 Setup
50 ^^^^^
51
52 Activate the plugin by adding ``'sphinx.ext.autodoc'`` to
53 the :confval:`extensions` list in :file:`conf.py`:
54
55 .. code-block:: python
56
57 extensions = [
58 ...
59 'sphinx.ext.autodoc',
60 ]
61
62
63 Ensuring the code can be imported
64 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
65
66 :mod:`~sphinx.ext.autodoc` analyses the code and docstrings
67 by introspection after **importing the modules**.
68 For importing to work, you have to make sure that your modules can be found
69 by Sphinx and that dependencies can be resolved
70 (if your module does ``import foo``, but ``foo`` is not available
71 in the python environment that Sphinx runs in, your module import will fail).
72
73 There are two ways to ensure this:
74
75 1. Use an environment that contains your package and Sphinx.
76 This can e.g. be your local development environment (with an editable install),
77 or an environment in CI in which you install Sphinx and your package.
78 The regular installation process ensures that your package can be found
79 by Sphinx and that all dependencies are available.
80
81 2. It is alternatively possible to patch the Sphinx run so that it can operate
82 directly on the sources;
83 e.g. if you want to be able to do a Sphinx build from a source checkout.
84
85 * Patch :data:`sys.path` in :file:`conf.py` to include your source path.
86 For example if you have a repository structure with :file:`doc/conf.py`
87 and your package is at :file:`src/my_package`,
88 then you should add the following to your :file:`conf.py`.
89
90 .. code-block:: python
91
92 import sys
93 from pathlib import Path
94
95 sys.path.insert(0, str(Path('..', 'src').resolve()))
96
97 * To cope with missing dependencies, specify the missing modules in
98 the :confval:`autodoc_mock_imports` setting.
99
100
101 Usage
102 ^^^^^
103
104 You can now use the :ref:`autodoc-directives` to add formatted documentation
105 for Python code elements like functions, classes, modules, etc.
106 For example, to document the function ``io.open()``,
107 reading its signature and docstring from the source file, you'd write:
108
109 .. code-block:: rst
110
111 .. autofunction:: io.open
112
113 You can also document whole classes or even modules automatically,
114 using member options for the auto directives, like:
115
116 .. code-block:: rst
117
118 .. automodule:: io
119 :members:
120
121 .. tip::
122 As a hint to autodoc extension, you can put a ``::`` separator
123 between the module name and the object name
124 to let autodoc know the correct module, if it is ambiguous:
125
126 .. code-block:: rst
127
128 .. autoclass:: module.name::Noodle
129
130
131 Marking objects as public or private
132 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
133
134 * autodoc considers a member private if its docstring contains
135 ``:meta private:`` in its :ref:`info-field-lists`.
136 For example:
137
138 .. code-block:: python
139
140 def my_function(my_arg, my_other_arg):
141 """blah blah blah
142
143 :meta private:
144 """
145
146 .. versionadded:: 3.0
147
148 * autodoc considers a member public if its docstring contains
149 ``:meta public:`` in its :ref:`info-field-lists`, even if it starts with
150 an underscore.
151 For example:
152
153 .. code-block:: python
154
155 def _my_function(my_arg, my_other_arg):
156 """blah blah blah
157
158 :meta public:
159 """
160
161 .. versionadded:: 3.1
162
163 * autodoc considers a variable member does not have any default value if its
164 docstring contains ``:meta hide-value:`` in its :ref:`info-field-lists`.
165 Example:
166
167 .. code-block:: python
168
169 var1 = None #: :meta hide-value:
170
171 .. versionadded:: 3.5
172
173
174 .. _doc-comment:
175
176 Doc comments and docstrings
177 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
178
179 Python has no built-in support for docstrings for
180 module data members or class attributes.
181 To allow documenting these, ``autodoc`` recognises a special format of
182 :ref:`comment <python:comments>` called a 'doc comment' or 'documentation comment'.
183
184 These comments start with a colon and an optional space character,
185 ``'#:'`` or ``'#: '``.
186 To be recognised, the comments must appear either on the same line
187 as the variable or on one or more lines before the variable.
188 Multi-line doc-comments must always appear on the lines before the
189 variable's definition.
190
191 For example, all three of the following variables have valid doc-comments:
192
193 .. code-block:: python
194
195 egg_and_spam = 1.50 #: A simple meal
196
197 #: Spam! Lovely spam! Lovely spam!
198 egg_bacon_sausage_and_spam = 2.49
199
200 #: Truly gourmet cuisine for madam; Lobster Thermidor
201 #: aux Crevettes with a mornay sauce garnished with
202 #: truffle pate, brandy and a fried egg on top and spam.
203 lobster_thermidor = 35.00
204
205 Alternatively, ``autodoc`` can recognise a docstring
206 on the line immediately following the definition.
207
208 In the the following class definition,
209 all attributes have documentation recognised by ``autodoc``:
210
211 .. code-block:: python
212
213 class Foo:
214 """Docstring for class Foo."""
215
216 #: Doc comment for class attribute Foo.bar.
217 #: It can have multiple lines.
218 bar = 1
219
220 flox = 1.5 #: Doc comment for Foo.flox. One line only.
221
222 baz = 2
223 """Docstring for class attribute Foo.baz."""
224
225 def __init__(self):
226 #: Doc comment for instance attribute qux.
227 self.qux = 3
228
229 self.spam = 4
230 """Docstring for instance attribute spam."""
231
232
233 .. _autodoc-directives:
234
235 Directives
236 ----------
237
238 :mod:`autodoc` provides several directives that are versions of
239 the usual :rst:dir:`py:module`, :rst:dir:`py:class` and so forth.
240 On parsing time, they import the corresponding module
241 and extract the docstring of the given objects,
242 inserting them into the page source under a suitable
243 :rst:dir:`py:module`, :rst:dir:`py:class` etc. directive.
244
245 .. note::
246
247 Just as :rst:dir:`py:class` respects the current
248 :rst:dir:`py:module`, :rst:dir:`autoclass` will also do so.
249 Likewise, :rst:dir:`automethod` will respect the current :rst:dir:`py:class`.
250
251
252 Default directive options
253 ^^^^^^^^^^^^^^^^^^^^^^^^^
254
255 To make any of the options described below the default,
256 use the :confval:`autodoc_default_options` dictionary in :file:`conf.py`.
257
258 If using defaults for the ``:members:``, ``:exclude-members:``,
259 ``:private-members:``, or ``:special-members:`` options,
260 setting the option on a directive will override the default.
261 Instead, to extend the default list with the per-directive option,
262 the list may be prepended with a plus sign (``+``),
263 as follows:
264
265 .. code-block:: rst
266
267 .. autoclass:: Noodle
268 :members: eat
269 :private-members: +_spicy, _garlickly
270
271 .. tip::
272 If using :confval:`autodoc_default_options`,
273 the defaults can be disabled per-directive with the negated form,
274 :samp:`:no-{option}:` as an option of the directive
275 For example:
276
277 .. code-block:: rst
278
279 .. automodule:: foo
280 :no-undoc-members:
281
282
283 Automatically document modules
284 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
285
286 .. rst:directive:: automodule
287
288 Document a module.
289 By default, the directive only inserts the docstring of the module itself:
290
291 .. code-block:: rst
292
293 .. automodule:: noodles
294
295 will produce source like this:
296
297 .. code-block:: rst
298
299 .. py:module:: noodles
300
301 The noodles module.
302
303 The directive can also contain content of its own,
304 which will be inserted into the resulting non-auto directive source
305 after the docstring (but before any automatic member documentation).
306
307 Therefore, you can also mix automatic and non-automatic member documentation,
308 as follows:
309
310 .. code-block:: rst
311
312 .. automodule:: noodles
313 :members: Noodle
314
315 .. py:function:: boiled_noodle(time=10)
316
317 Create a noodle that has been boiled for *time* minutes.
318
319 .. rubric:: Options
320
321 .. rst:directive:option:: no-index
322 :type:
323
324 Do not generate an index entry for the documented module
325 or any auto-documented members.
326
327 .. versionadded:: 0.4
328
329 .. rst:directive:option:: no-index-entry
330 :type:
331
332 Do not generate an index entry for the documented module
333 or any auto-documented members.
334 Unlike ``:no-index:``, cross-references are still created.
335
336 .. versionadded:: 8.2
337
338 .. rst:directive:option:: platform: platforms
339 :type: comma separated list
340
341 Indicate platforms on which the module is available.
342 This is identical to :rst:dir:`py:module`'s ``:platform:`` option.
343
344 .. rst:directive:option:: synopsis: purpose
345 :type: text
346
347 A sentence describing the module's purpose.
348 This is identical to :rst:dir:`py:module`'s ``:synopsis:`` option.
349
350 .. versionadded:: 0.5
351
352 .. rst:directive:option:: deprecated
353 :type:
354
355 Mark a module as deprecated.
356 This is identical to :rst:dir:`py:module`'s ``:deprecated:`` option.
357
358 .. versionadded:: 0.5
359
360 .. rst:directive:option:: ignore-module-all
361 :type: no value
362
363 Do not use ``__all__`` when analysing the module to document.
364
365 .. versionadded:: 1.7
366
367 .. rubric:: Options for selecting members to document
368
369 .. rst:directive:option:: members
370 :type: no value or comma separated list
371
372 Generate automatic documentation for all members of the target module:
373
374 .. code-block:: rst
375
376 .. automodule:: noodles
377 :members:
378
379 By default, ``autodoc`` only includes public members
380 with a docstring or :ref:`doc-comment <doc-comment>` (``#:``).
381 If ``__all__`` exists, it will be used to define which members are public,
382 unless the :rst:dir:`:ignore-module-all: <automodule:ignore-module-all>`
383 option is set.
384
385 To only document certain members, an explicit comma-separated list
386 may be used as the argument to ``:members:``:
387
388 .. code-block:: rst
389
390 .. automodule:: noodles
391 :members: Noodle
392
393 .. rst:directive:option:: exclude-members
394 :type: comma separated list
395
396 Exclude the given names from the members to document.
397 For example:
398
399 .. code-block:: rst
400
401 .. automodule:: noodles
402 :members:
403 :exclude-members: NoodleBase
404
405 .. versionadded:: 0.6
406
407 .. rst:directive:option:: imported-members
408 :type: no value
409
410 To prevent documentation of imported classes or functions,
411 in an :rst:dir:`!automodule` directive with the ``members`` option set,
412 only module members where the ``__module__`` attribute is equal
413 to the module name given to ``automodule`` will be documented.
414
415 Set the ``imported-members`` option if you want to prevent this behavior
416 and document all available members.
417
418 Note that attributes from imported modules will not be documented,
419 because attribute documentation is discovered by
420 parsing the source file of the current module.
421
422 .. versionadded:: 1.2
423
424 .. rst:directive:option:: undoc-members
425 :type:
426
427 Generate automatic documentation for members of the target module
428 that don't have a docstring or doc-comment.
429 For example:
430
431 .. code-block:: rst
432
433 .. automodule:: noodles
434 :members:
435 :undoc-members:
436
437 .. rst:directive:option:: private-members
438 :type: no value or comma separated list
439
440 Generate automatic documentation for private members of the target module.
441 This includes names with a leading underscore (e.g. ``_private``)
442 and those members explicitly marked as private with ``:meta private:``.
443
444 .. code-block:: rst
445
446 .. automodule:: noodles
447 :members:
448 :private-members:
449
450 To only document certain private members, an explicit comma-separated list
451 may be used as the argument to ``:private-members:``:
452
453 .. code-block:: rst
454
455 .. automodule:: noodles
456 :members:
457 :private-members: _spicy, _garlickly
458
459 .. versionadded:: 1.1
460 .. versionchanged:: 3.2
461 The option can now take a comma-separated list of arguments.
462
463 .. rst:directive:option:: special-members
464 :type: no value or comma separated list
465
466 Generate automatic documentation for special members of the target module,
467 also known as :ref:`'dunder' names <python:specialnames>`.
468 This includes all names enclosed with a double-underscore,
469 e.g. ``__special__``:
470
471 .. code-block:: rst
472
473 .. automodule:: my.Class
474 :members:
475 :special-members:
476
477 To only document certain special members, an explicit comma-separated list
478 may be used as the argument to ``:special-members:``:
479
480 .. code-block:: rst
481
482 .. automodule:: noodles
483 :members:
484 :special-members: __version__
485
486 .. versionadded:: 1.1
487
488 .. versionchanged:: 1.2
489 The option can now take a comma-separated list of arguments.
490
491 .. rubric:: Options for documented members
492
493 .. rst:directive:option:: member-order
494 :type: alphabetical, bysource, or groupwise
495
496 Choose the ordering of automatically documented members
497 (default: ``alphabetical``).
498 This overrides the :confval:`autodoc_member_order` setting.
499
500 * ``alphabetical``:
501 Use simple alphabetical order.
502 * ``groupwise``:
503 Group by object type (class, function, etc),
504 use alphabetical order within groups.
505 * ``bysource``:
506 Use the order of objects in the module's source.
507 The ``__all__`` variable can be used to override this order.
508
509 Note that for source order, the module must be a Python module with the
510 source code available.
511
512 .. versionadded:: 0.6
513 .. versionchanged:: 1.0
514 Support the ``'bysource'`` option.
515
516 .. rst:directive:option:: show-inheritance
517 :type: no value
518
519 Enable the :rst:dir:`:show-inheritance: <autoclass:show-inheritance>`
520 option for all members of the module,
521 if ``:members:`` is enabled.
522
523 .. versionadded:: 0.4
524
525
526 Automatically document classes or exceptions
527 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
528
529 .. rst:directive:: autoclass
530 autoexception
531
532 Document a class.
533 For exception classes, prefer ``.. autoexception::``.
534 By default, the directive only inserts the docstring of the class itself:
535
536 .. code-block:: rst
537
538 .. autoclass:: noodles.Noodle
539
540 will produce source like this:
541
542 .. code-block:: rst
543
544 .. py:class:: Noodle
545
546 The Noodle class's docstring.
547
548 The directive can also contain content of its own,
549 which will be inserted into the resulting non-auto directive source
550 after the docstring (but before any automatic member documentation).
551
552 Therefore, you can also mix automatic and non-automatic member documentation,
553 as follows:
554
555 .. code-block:: rst
556
557 .. autoclass:: noodles.Noodle
558 :members: eat, slurp
559
560 .. py:method:: boil(time=10)
561
562 Boil the noodle for *time* minutes.
563
564 .. rubric:: Advanced usage
565
566 * It is possible to override the signature for explicitly documented
567 callable objects (functions, methods, classes) with the regular syntax
568 that will override the signature gained from introspection:
569
570 .. code-block:: rst
571
572 .. autoclass:: noodles.Noodle(type)
573
574 .. automethod:: eat(persona)
575
576 This is useful if the signature from the method is hidden by a decorator.
577
578 .. versionadded:: 0.4
579
580 .. rubric:: Options
581
582 .. rst:directive:option:: no-index
583 :type:
584
585 Do not generate an index entry for the documented class
586 or any auto-documented members.
587
588 .. versionadded:: 0.4
589
590 .. rst:directive:option:: no-index-entry
591 :type:
592
593 Do not generate an index entry for the documented class
594 or any auto-documented members.
595 Unlike ``:no-index:``, cross-references are still created.
596
597 .. versionadded:: 8.2
598
599 .. rst:directive:option:: class-doc-from
600 :type: class, init, or both
601
602 Select which docstring will be used for the main body of the directive.
603 This overrides the global value of :confval:`autoclass_content`.
604 The possible values are:
605
606 * ``class``:
607 Only use the class's docstring.
608 The :meth:`!__init__` method can be separately documented
609 using the ``:members:`` option or :rst:dir:`automethod`.
610 * ``init``:
611 Only use the docstring of the :meth:`!__init__` method.
612 * ``both``:
613 Use both, appending the docstring of the :meth:`!__init__` method
614 to the class's docstring.
615
616 If the :meth:`!__init__` method doesn't exist or has a blank docstring,
617 ``autodoc`` will attempt to use the :meth:`!__new__` method's docstring,
618 if it exists and is not blank.
619
620 .. versionadded:: 4.1
621
622 .. rubric:: Options for selecting members to document
623
624 .. rst:directive:option:: members
625 :type: no value or comma separated list
626
627 Generate automatic documentation for all members of the target class:
628
629 .. code-block:: rst
630
631 .. autoclass:: noodles.Noodle
632 :members:
633
634 By default, ``autodoc`` only includes public members
635 with a docstring or :ref:`doc-comment <doc-comment>` (``#:``)
636 that are attributes of the target class (i.e. not inherited).
637
638 To only document certain members, an explicit comma-separated list
639 may be used as the argument to ``:members:``:
640
641 .. code-block:: rst
642
643 .. autoclass:: noodles.Noodle
644 :members: eat, slurp
645
646 .. rst:directive:option:: exclude-members
647 :type: comma separated list
648
649 Exclude the given names from the members to document.
650 For example:
651
652 .. code-block:: rst
653
654 .. autoclass:: noodles.Noodle
655 :members:
656 :exclude-members: prepare
657
658 .. versionadded:: 0.6
659
660 .. rst:directive:option:: inherited-members
661 :type: comma separated list
662
663 To generate automatic documentation for members inherited
664 from base classes, use the ``:inherited-members:`` option:
665
666 .. code-block:: rst
667
668 .. autoclass:: noodles.Noodle
669 :members:
670 :inherited-members:
671
672 This can be combined with the ``:undoc-members:`` option to generate
673 automatic documentation for *all* available members of the class.
674
675 The members of classes listed in the argument to ``:inherited-members:``
676 are excluded from the automatic documentation.
677 This defaults to :py:class:`python:object` if no argument is provided,
678 meaning that members of the ``object`` class are not documented.
679 To include these, use ``None`` as the argument.
680
681 For example; If your class ``MyList`` is derived from ``list`` class and
682 you don't want to document ``list.__len__()``, you should specify a
683 option ``:inherited-members: list`` to avoid special members of list
684 class.
685
686 .. note::
687 Should any of the inherited members use a format other than
688 reStructuredText for their docstrings,
689 there may be markup warnings or errors.
690
691 .. versionadded:: 0.3
692
693 .. versionchanged:: 3.0
694 ``:inherited-members:`` now takes the name of a base class
695 to exclude as an argument.
696
697 .. versionchanged:: 5.0
698 A comma separated list of base class names can be used.
699
700 .. rst:directive:option:: undoc-members
701 :type: no value
702
703 Generate automatic documentation for members of the target class
704 that don't have a docstring or doc-comment.
705 For example:
706
707 .. code-block:: rst
708
709 .. autoclass:: noodles.Noodle
710 :members:
711 :undoc-members:
712
713 .. rst:directive:option:: private-members
714 :type: no value or comma separated list
715
716 Generate automatic documentation for private members of the target class.
717 This includes names with a leading underscore (e.g. ``_private``)
718 and those members explicitly marked as private with ``:meta private:``.
719
720 .. code-block:: rst
721
722 .. autoclass:: noodles.Noodle
723 :members:
724 :private-members:
725
726 To only document certain private members, an explicit comma-separated list
727 may be used as the argument to ``:private-members:``:
728
729 .. code-block:: rst
730
731 .. autoclass:: noodles.Noodle
732 :members:
733 :private-members: _spicy, _garlickly
734
735 .. versionadded:: 1.1
736 .. versionchanged:: 3.2
737 The option can now take arguments.
738
739 .. rst:directive:option:: special-members
740 :type: no value or comma separated list
741
742 Generate automatic documentation for special members of the target class,
743 also known as :ref:`'dunder' names <python:specialnames>`.
744 This includes all names enclosed with a double-underscore,
745 e.g. ``__special__``:
746
747 .. code-block:: rst
748
749 .. autoclass:: noodles.Noodle
750 :members:
751 :special-members:
752
753 To only document certain special members, an explicit comma-separated list
754 may be used as the argument to ``:special-members:``:
755
756 .. code-block:: rst
757
758 .. autoclass:: noodles.Noodle
759 :members:
760 :special-members: __init__, __name__
761
762 .. versionadded:: 1.1
763
764 .. versionchanged:: 1.2
765 The option can now take a comma-separated list of arguments.
766
767 .. rubric:: Options for documented members
768
769 .. rst:directive:option:: member-order
770 :type: alphabetical, bysource, or groupwise
771
772 Choose the ordering of automatically documented members
773 (default: ``alphabetical``).
774 This overrides the :confval:`autodoc_member_order` setting.
775
776 * ``'alphabetical'``:
777 Use simple alphabetical order.
778 * ``'groupwise'``:
779 Group by object type (class, function, etc),
780 use alphabetical order within groups.
781 * ``'bysource'``:
782 Use the order of objects in the module's source.
783 The ``__all__`` variable can be used to override this order.
784
785 Note that for source order, the module must be a Python module with the
786 source code available.
787
788 .. versionadded:: 0.6
789 .. versionchanged:: 1.0
790 Support the ``'bysource'`` option.
791
792 .. rst:directive:option:: show-inheritance
793 :type: no value
794
795 Insert the class's base classes after the class signature.
796
797 .. versionadded:: 0.4
798
799
800 Automatically document function-like objects
801 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
802
803 .. rst:directive:: autofunction
804 automethod
805 autoproperty
806 autodecorator
807
808 Document a function, method, property, or decorator.
809 By default, the directive only inserts the docstring of the function itself:
810
811 .. code-block:: rst
812
813 .. autofunction:: noodles.average_noodle
814
815 will produce source like this:
816
817 .. code-block:: rst
818
819 .. py:function:: noodles.average_noodle
820
821 The average_noodle function's docstring.
822
823 The directive can also contain content of its own,
824 which will be inserted into the resulting non-auto directive source
825 after the docstring.
826
827 Therefore, you can also mix automatic and non-automatic documentation,
828 as follows:
829
830 .. code-block:: rst
831
832 .. autofunction:: noodles.average_noodle
833
834 .. note:: For more flexibility, use the :py:class:`!Noodle` class.
835
836 .. versionadded:: 2.0
837 :rst:dir:`autodecorator`.
838 .. versionadded:: 2.1
839 :rst:dir:`autoproperty`.
840
841 .. note::
842
843 If you document decorated functions or methods,
844 keep in mind that ``autodoc`` retrieves its docstrings
845 by importing the module and inspecting the ``__doc__`` attribute
846 of the given function or method.
847 That means that if a decorator replaces the decorated function with another,
848 it must copy the original ``__doc__`` to the new function.
849
850 .. rubric:: Advanced usage
851
852 * It is possible to override the signature for explicitly documented
853 callable objects (functions, methods, classes) with the regular syntax
854 that will override the signature gained from introspection:
855
856 .. code-block:: rst
857
858 .. autoclass:: Noodle(type)
859
860 .. automethod:: eat(persona)
861
862 This is useful if the signature from the method is hidden by a decorator.
863
864 .. versionadded:: 0.4
865
866 .. rubric:: Options
867
868 .. rst:directive:option:: no-index
869 :type:
870
871 Do not generate an index entry for the documented function.
872
873 .. versionadded:: 0.4
874
875 .. rst:directive:option:: no-index-entry
876 :type:
877
878 Do not generate an index entry for the documented function.
879 Unlike ``:no-index:``, cross-references are still created.
880
881 .. versionadded:: 8.2
882
883
884 Automatically document attributes or data
885 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
886
887 .. rst:directive:: autodata
888 autoattribute
889
890 Document a module level variable or constant ('data') or class attribute.
891 By default, the directive only inserts the docstring of the variable itself:
892
893 .. code-block:: rst
894
895 .. autodata:: noodles.FLOUR_TYPE
896
897 will produce source like this:
898
899 .. code-block:: rst
900
901 .. py:data:: noodles.FLOUR_TYPE
902
903 The FLOUR_TYPE constant's docstring.
904
905 The directive can also contain content of its own,
906 which will be inserted into the resulting non-auto directive source
907 after the docstring.
908
909 Therefore, you can also mix automatic and non-automatic member documentation,
910 as follows:
911
912 .. code-block:: rst
913
914 .. autodata:: noodles.FLOUR_TYPE
915
916 .. hint:: Cooking time can vary by which flour type is used.
917
918 .. versionchanged:: 0.6
919 :rst:dir:`autodata` and :rst:dir:`autoattribute`
920 can now extract docstrings.
921 .. versionchanged:: 1.1
922 Doc-comments are now allowed on the same line of an assignment.
923
924 .. rubric:: Options
925
926 .. rst:directive:option:: no-index
927 :type:
928
929 Do not generate an index entry for the documented variable or constant.
930
931 .. versionadded:: 0.4
932
933 .. rst:directive:option:: no-index-entry
934 :type:
935
936 Do not generate an index entry for the documented variable or constant.
937 Unlike ``:no-index:``, cross-references are still created.
938
939 .. versionadded:: 8.2
940
941 .. rst:directive:option:: annotation: value
942 :type: string
943
944 .. versionadded:: 1.2
945
946 By default, ``autodoc`` attempts to obtain the type annotation
947 and value of the variable by introspection,
948 displaying it after the variable's name.
949 To override this, a custom string for the variable's value
950 may be used as the argument to ``annotation``.
951
952 For example, if the runtime value of ``FILE_MODE`` is ``0o755``,
953 the displayed value will be ``493`` (as ``oct(493) == '0o755'``).
954 This can be fixed by setting ``:annotation: = 0o755``.
955
956 If ``:annotation:`` is used without arguments,
957 no value or type hint will be shown for the variable.
958
959 .. rst:directive:option:: no-value
960
961 .. versionadded:: 3.4
962
963 To display the type hint of the variable without a value,
964 use the ``:no-value:`` option.
965 If both the ``:annotation:`` and ``:no-value:`` options are used,
966 ``:no-value:`` has no effect.
967
968
969 Automatically document type aliases
970 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
971
972 .. rst:directive:: autotype
973
974 .. versionadded:: 9.0
975
976 Document a :pep:`695` type alias (the :keyword:`type` statement).
977 By default, the directive only inserts the docstring of the alias itself:
978
979 The directive can also contain content of its own,
980 which will be inserted into the resulting non-auto directive source
981 after the docstring (but before any automatic member documentation).
982
983 Therefore, you can also mix automatic and non-automatic member documentation.
984
985 .. rubric:: Options
986
987 .. rst:directive:option:: no-index
988 :type:
989
990 Do not generate an index entry for the documented class
991 or any auto-documented members.
992
993 .. rst:directive:option:: no-index-entry
994 :type:
995
996 Do not generate an index entry for the documented class
997 or any auto-documented members.
998 Unlike ``:no-index:``, cross-references are still created.
999
1000
1001 Configuration
1002 -------------
1003
1004 There are also config values that you can set:
1005
1006 .. confval:: autodoc_use_legacy_class_based
1007 :type: :code-py:`bool`
1008 :default: :code-py:`False`
1009
1010 If true, autodoc will use the legacy class-based implementation.
1011 This is the behaviour prior to Sphinx 9.0.
1012 It is based on the ``Documenter`` class hierarchy.
1013
1014 This setting is provided for backwards compatibility if your documentation
1015 or an extension you use uses or monkeypatches the legacy class-based API
1016 in Python code.
1017 If this is the case, set ``autodoc_use_legacy_class_based = True``
1018 in your :file:`conf.py`.
1019 Please also add a comment to `the tracking issue on GitHub
1020 <https://github.com/sphinx-doc/sphinx/issues/14089>`__ so that the maintainers
1021 are aware of your use case, for possible future improvements.
1022
1023 .. note:: The legacy class-based implementation does not support
1024 PEP 695 type aliases.
1025
1026 .. confval:: autoclass_content
1027 :type: :code-py:`str`
1028 :default: :code-py:`'class'`
1029
1030 This value selects what content will be inserted into the main body of an
1031 :rst:dir:`autoclass` directive. The possible values are:
1032
1033 ``'class'``
1034 Only the class' docstring is inserted. You can
1035 still document ``__init__`` as a separate method using
1036 :rst:dir:`automethod` or the ``members`` option to :rst:dir:`autoclass`.
1037 ``'both'``
1038 Both the class' and the ``__init__`` method's docstring are concatenated
1039 and inserted.
1040 ``'init'``
1041 Only the ``__init__`` method's docstring is inserted.
1042
1043 .. versionadded:: 0.3
1044
1045 If the class has no ``__init__`` method or if the ``__init__`` method's
1046 docstring is empty, but the class has a ``__new__`` method's docstring,
1047 it is used instead.
1048
1049 .. versionadded:: 1.4
1050
1051 .. confval:: autodoc_class_signature
1052 :type: :code-py:`str`
1053 :default: :code-py:`'mixed'`
1054
1055 This value selects how the signature will be displayed for the class defined
1056 by :rst:dir:`autoclass` directive. The possible values are:
1057
1058 ``'mixed'``
1059 Display the signature with the class name.
1060 ``'separated'``
1061 Display the signature as a method.
1062
1063 .. versionadded:: 4.1
1064
1065 .. confval:: autodoc_member_order
1066 :type: :code-py:`str`
1067 :default: :code-py:`'alphabetical'`
1068
1069 Define the order in which :rst:dir:`automodule` and :rst:dir:`autoclass`
1070 members are listed. Supported values are:
1071
1072 * ``'alphabetical'``:
1073 Use alphabetical order.
1074
1075 * ``'groupwise'``: order by member type. The order is:
1076
1077 * for modules, exceptions, classes, functions, data
1078 * for classes: class methods, static methods, methods,
1079 and properties/attributes
1080
1081 Members are ordered alphabetically within groups.
1082
1083 * ``'bysource'``:
1084 Use the order in which the members appear in the source code.
1085 This requires that the module must be a Python module with the
1086 source code available.
1087
1088 .. versionadded:: 0.6
1089 .. versionchanged:: 1.0
1090 Support for ``'bysource'``.
1091
1092 .. confval:: autodoc_default_options
1093 :type: :code-py:`dict[str, str | bool]`
1094 :default: :code-py:`{}`
1095
1096 The default options for autodoc directives. They are applied to all autodoc
1097 directives automatically. It must be a dictionary which maps option names
1098 to the values. For example:
1099
1100 .. code-block:: python
1101
1102 autodoc_default_options = {
1103 'members': 'var1, var2',
1104 'member-order': 'bysource',
1105 'special-members': '__init__',
1106 'undoc-members': True,
1107 'exclude-members': '__weakref__'
1108 }
1109
1110 Setting ``None`` or ``True`` to the value is equivalent to giving only the
1111 option name to the directives.
1112
1113 The supported options are:
1114
1115 * ``'members'``: See :rst:dir:`automodule:members`.
1116 * ``'undoc-members'`` See :rst:dir:`automodule:undoc-members`.
1117 * ``'private-members'``: See :rst:dir:`automodule:private-members`.
1118 * ``'special-members'``: See :rst:dir:`automodule:special-members`.
1119 * ``'inherited-members'``: See :rst:dir:`autoclass:inherited-members`.
1120 * ``'imported-members'``: See :rst:dir:`automodule:imported-members`.
1121 * ``'exclude-members'``: See :rst:dir:`automodule:exclude-members`.
1122 * ``'ignore-module-all'``: See :rst:dir:`automodule:ignore-module-all`.
1123 * ``'member-order'``: See :rst:dir:`automodule:member-order`.
1124 * ``'show-inheritance'``: See :rst:dir:`autoclass:show-inheritance`.
1125 * ``'class-doc-from'``: See :rst:dir:`autoclass:class-doc-from`.
1126 * ``'no-value'``: See :rst:dir:`autodata:no-value`.
1127 * ``'no-index'``: See :rst:dir:`automodule:no-index`.
1128 * ``'no-index-entry'``: See :rst:dir:`automodule:no-index-entry`.
1129
1130 .. versionadded:: 1.8
1131
1132 .. versionchanged:: 2.0
1133 Accepts ``True`` as a value.
1134
1135 .. versionchanged:: 2.1
1136 Added ``'imported-members'``.
1137
1138 .. versionchanged:: 4.1
1139 Added ``'class-doc-from'``.
1140
1141 .. versionchanged:: 4.5
1142 Added ``'no-value'``.
1143
1144 .. confval:: autodoc_docstring_signature
1145 :type: :code-py:`bool`
1146 :default: :code-py:`True`
1147
1148 Functions imported from C modules cannot be introspected, and therefore the
1149 signature for such functions cannot be automatically determined. However, it
1150 is an often-used convention to put the signature into the first line of the
1151 function's docstring.
1152
1153 If this boolean value is set to ``True`` (which is the default), autodoc will
1154 look at the first line of the docstring for functions and methods, and if it
1155 looks like a signature, use the line as the signature and remove it from the
1156 docstring content.
1157
1158 autodoc will continue to look for multiple signature lines,
1159 stopping at the first line that does not look like a signature.
1160 This is useful for declaring overloaded function signatures.
1161
1162 .. versionadded:: 1.1
1163 .. versionchanged:: 3.1
1164
1165 Support overloaded signatures
1166
1167 .. versionchanged:: 4.0
1168
1169 Overloaded signatures do not need to be separated by a backslash
1170
1171 .. confval:: autodoc_mock_imports
1172 :type: :code-py:`list[str]`
1173 :default: :code-py:`[]`
1174
1175 This value contains a list of modules to be mocked up. This is useful when
1176 some external dependencies are not met at build time and break the building
1177 process. You may only specify the root package of the dependencies
1178 themselves and omit the sub-modules:
1179
1180 .. code-block:: python
1181
1182 autodoc_mock_imports = ['django']
1183
1184 Will mock all imports under the ``django`` package.
1185
1186 .. versionadded:: 1.3
1187
1188 .. versionchanged:: 1.6
1189 This config value only requires to declare the top-level modules that
1190 should be mocked.
1191
1192 .. confval:: autodoc_typehints
1193 :type: :code-py:`str`
1194 :default: :code-py:`'signature'`
1195
1196 This value controls how to represent typehints. The setting takes the
1197 following values:
1198
1199 * ``'signature'`` -- Show typehints in the signature
1200 * ``'description'`` -- Show typehints as content of the function or method
1201 The typehints of overloaded functions or methods will still be represented
1202 in the signature.
1203 * ``'none'`` -- Do not show typehints
1204 * ``'both'`` -- Show typehints in the signature and as content of
1205 the function or method
1206
1207 Overloaded functions or methods will not have typehints included in the
1208 description because it is impossible to accurately represent all possible
1209 overloads as a list of parameters.
1210
1211 .. versionadded:: 2.1
1212 .. versionadded:: 3.0
1213
1214 New option ``'description'`` is added.
1215
1216 .. versionadded:: 4.1
1217
1218 New option ``'both'`` is added.
1219
1220 .. confval:: autodoc_typehints_description_target
1221 :type: :code-py:`str`
1222 :default: :code-py:`'all'`
1223
1224 This value controls whether the types of
1225 undocumented parameters and return values are documented
1226 when :confval:`autodoc_typehints` is set to ``'description'``.
1227 Supported values:
1228
1229 * ``'all'``:
1230 Types are documented for all parameters and return values,
1231 whether they are documented or not.
1232 * ``'documented'``:
1233 Types will only be documented for a parameter
1234 or a return value that is already documented by the docstring.
1235 * ``'documented_params'``:
1236 Parameter types will only be annotated if the
1237 parameter is documented in the docstring. The return type is always
1238 annotated (except if it is ``None``).
1239
1240 .. versionadded:: 4.0
1241
1242 .. versionadded:: 5.0
1243
1244 New option ``'documented_params'`` is added.
1245
1246 .. confval:: autodoc_type_aliases
1247 :type: :code-py:`dict[str, str]`
1248 :default: :code-py:`{}`
1249
1250 A dictionary for users defined `type aliases`__ that maps a type name to the
1251 full-qualified object name. It is used to keep type aliases not evaluated in
1252 the document.
1253
1254 The type aliases are only available if your program enables :pep:`Postponed
1255 Evaluation of Annotations (PEP 563) <563>` feature via ``from __future__ import
1256 annotations``.
1257
1258 For example, there is code using a type alias:
1259
1260 .. code-block:: python
1261
1262 from __future__ import annotations
1263
1264 AliasType = Union[List[Dict[Tuple[int, str], Set[int]]], Tuple[str, List[str]]]
1265
1266 def f() -> AliasType:
1267 ...
1268
1269 If ``autodoc_type_aliases`` is not set, autodoc will generate internal mark-up
1270 from this code as following:
1271
1272 .. code-block:: rst
1273
1274 .. py:function:: f() -> Union[List[Dict[Tuple[int, str], Set[int]]], Tuple[str, List[str]]]
1275
1276 ...
1277
1278 If you set ``autodoc_type_aliases`` as
1279 ``{'AliasType': 'your.module.AliasType'}``, it generates the following document
1280 internally:
1281
1282 .. code-block:: rst
1283
1284 .. py:function:: f() -> your.module.AliasType:
1285
1286 ...
1287
1288 .. __: https://mypy.readthedocs.io/en/latest/kinds_of_types.html#type-aliases
1289 .. versionadded:: 3.3
1290
1291 .. confval:: autodoc_typehints_format
1292 :type: :code-py:`str`
1293 :default: :code-py:`'short'`
1294
1295 This value controls the format of typehints. The setting takes the
1296 following values:
1297
1298 * ``'fully-qualified'`` -- Show the module name and its name of typehints
1299 * ``'short'`` -- Suppress the leading module names of the typehints
1300 (e.g. ``io.StringIO`` -> ``StringIO``)
1301
1302 .. versionadded:: 4.4
1303
1304 .. versionchanged:: 5.0
1305
1306 The default setting was changed to ``'short'``
1307
1308 .. confval:: autodoc_preserve_defaults
1309 :type: :code-py:`bool`
1310 :default: :code-py:`False`
1311
1312 If True, the default argument values of functions will be not evaluated on
1313 generating document. It preserves them as is in the source code.
1314
1315 .. versionadded:: 4.0
1316
1317 Added as an experimental feature. This will be integrated into autodoc core
1318 in the future.
1319
1320 .. confval:: autodoc_use_type_comments
1321 :type: :code-py:`bool`
1322 :default: :code-py:`True`
1323
1324 Attempt to read ``# type: ...`` comments from source code
1325 to supplement missing type annotations, if True.
1326
1327 This can be disabled if your source code does not use type comments,
1328 for example if it exclusively uses type annotations or
1329 does not use type hints of any kind.
1330
1331 .. versionadded:: 8.2
1332
1333 Added the option to disable the use of type comments in
1334 via the new :confval:`!autodoc_use_type_comments` option,
1335 which defaults to :code-py:`True` for backwards compatibility.
1336 The default will change to :code-py:`False` in Sphinx 10.
1337
1338 .. xref RemovedInSphinx10Warning
1339
1340 .. confval:: autodoc_warningiserror
1341 :type: :code-py:`bool`
1342 :default: :code-py:`True`
1343
1344 This value controls the behavior of :option:`sphinx-build --fail-on-warning`
1345 during importing modules.
1346 If ``False`` is given, autodoc forcedly suppresses the error if the imported
1347 module emits warnings.
1348
1349 .. versionchanged:: 8.1
1350 This option now has no effect as :option:`!--fail-on-warning`
1351 no longer exits early.
1352
1353 .. confval:: autodoc_inherit_docstrings
1354 :type: :code-py:`bool`
1355 :default: :code-py:`True`
1356
1357 This value controls the docstrings inheritance.
1358 If set to True the docstring for classes or methods, if not explicitly set,
1359 is inherited from parents.
1360
1361 .. versionadded:: 1.7
1362
1363 .. confval:: suppress_warnings
1364 :no-index:
1365 :type: :code-py:`Sequence[str]`
1366 :default: :code-py:`()`
1367
1368 :mod:`autodoc` supports suppressing warning messages
1369 via :confval:`suppress_warnings`.
1370 It defines the following additional warnings types:
1371
1372 * autodoc
1373 * autodoc.import_object
1374
1375
1376 Docstring preprocessing
1377 -----------------------
1378
1379 autodoc provides the following additional events:
1380
1381 .. event:: autodoc-process-docstring (app, obj_type, name, obj, options, lines)
1382
1383 .. versionadded:: 0.4
1384
1385 Emitted when autodoc has read and processed a docstring. *lines* is a list
1386 of strings -- the lines of the processed docstring -- that the event handler
1387 can modify **in place** to change what Sphinx puts into the output.
1388
1389 :param app: the Sphinx application object
1390 :param obj_type: the type of the object which the docstring belongs to (one of
1391 ``'module'``, ``'class'``, ``'exception'``, ``'function'``, ``'decorator'``,
1392 ``'method'``, ``'property'``, ``'attribute'``, ``'data'``, or ``'type'``)
1393 :param name: the fully qualified name of the object
1394 :param obj: the object itself
1395 :param options: the options given to the directive: an object with attributes
1396 corresponding to the options used in the auto directive, e.g.
1397 ``inherited_members``, ``undoc_members``, or ``show_inheritance``.
1398 :param lines: the lines of the docstring, see above
1399
1400 .. event:: autodoc-before-process-signature (app, obj, bound_method)
1401
1402 .. versionadded:: 2.4
1403
1404 Emitted before autodoc formats a signature for an object. The event handler
1405 can modify an object to change its signature.
1406
1407 :param app: the Sphinx application object
1408 :param obj: the object itself
1409 :param bound_method: a boolean indicates an object is bound method or not
1410
1411 .. event:: autodoc-process-signature (app, obj_type, name, obj, options, signature, return_annotation)
1412
1413 .. versionadded:: 0.5
1414
1415 Emitted when autodoc has formatted a signature for an object. The event
1416 handler can return a new tuple ``(signature, return_annotation)`` to change
1417 what Sphinx puts into the output.
1418
1419 :param app: the Sphinx application object
1420 :param obj_type: the type of the object which the docstring belongs to (one of
1421 ``'module'``, ``'class'``, ``'exception'``, ``'function'``, ``'decorator'``,
1422 ``'method'``, ``'property'``, ``'attribute'``, ``'data'``, or ``'type'``)
1423 :param name: the fully qualified name of the object
1424 :param obj: the object itself
1425 :param options: the options given to the directive: an object with attributes
1426 corresponding to the options used in the auto directive, e.g.
1427 ``inherited_members``, ``undoc_members``, or ``show_inheritance``.
1428 :param signature: function signature, as a string of the form
1429 ``'(parameter_1, parameter_2)'``, or ``None`` if introspection didn't
1430 succeed and signature wasn't specified in the directive.
1431 :param return_annotation: function return annotation as a string of the form
1432 ``'annotation'``, or ``''`` if there is no return annotation.
1433
1434 The :mod:`sphinx.ext.autodoc` module provides factory functions for commonly
1435 needed docstring processing in event :event:`autodoc-process-docstring`:
1436
1437 .. autofunction:: cut_lines
1438 .. autofunction:: between
1439
1440 .. event:: autodoc-process-bases (app, name, obj, _unused, bases)
1441
1442 Emitted when autodoc has read and processed a class to determine the
1443 base-classes. *bases* is a list of classes that the event handler can
1444 modify **in place** to change what Sphinx puts into the output. It's
1445 emitted only if the ``show-inheritance`` option is given.
1446
1447 :param app: the Sphinx application object
1448 :param name: the fully qualified name of the object
1449 :param obj: the object itself
1450 :param _unused: unused placeholder
1451 :param bases: the list of base classes signature. see above.
1452
1453 .. versionadded:: 4.1
1454 .. versionchanged:: 4.3
1455
1456 ``bases`` can contain a string as a base class name.
1457 It will be processed as reStructuredText.
1458
1459
1460 Skipping members
1461 ----------------
1462
1463 autodoc allows the user to define a custom method for determining whether a
1464 member should be included in the documentation by using the following event:
1465
1466 .. event:: autodoc-skip-member (app, obj_type, name, obj, skip, options)
1467
1468 .. versionadded:: 0.5
1469
1470 Emitted when autodoc has to decide whether a member should be included in the
1471 documentation. The member is excluded if a handler returns ``True``. It is
1472 included if the handler returns ``False``.
1473
1474 If more than one enabled extension handles the ``autodoc-skip-member``
1475 event, autodoc will use the first non-``None`` value returned by a handler.
1476 Handlers should return ``None`` to fall back to the skipping behavior of
1477 autodoc and other enabled extensions.
1478
1479 :param app: the Sphinx application object
1480 :param obj_type: the type of the object which the docstring belongs to (one of
1481 ``'module'``, ``'class'``, ``'exception'``, ``'function'``, ``'decorator'``,
1482 ``'method'``, ``'property'``, ``'attribute'``, ``'data'``, or ``'type'``)
1483 :param name: the fully qualified name of the object
1484 :param obj: the object itself
1485 :param skip: a boolean indicating if autodoc will skip this member if the
1486 user handler does not override the decision
1487 :param options: the options given to the directive: an object with attributes
1488 corresponding to the options used in the auto directive, e.g.
1489 ``inherited_members``, ``undoc_members``, or ``show_inheritance``.