Debian Codegraph @

doc/usage/extensions/napoleon.rst

raw
1 :mod:`sphinx.ext.napoleon` -- Support for NumPy and Google style docstrings
2 ===========================================================================
3
4 .. module:: sphinx.ext.napoleon
5 :synopsis: Support for NumPy and Google style docstrings
6
7 .. moduleauthor:: Rob Ruana
8
9 .. versionadded:: 1.3
10
11 .. role:: code-py(code)
12 :language: Python
13
14 Overview
15 --------
16
17 Are you tired of writing docstrings that look like this:
18
19 .. code-block:: rst
20
21 :param path: The path of the file to wrap
22 :type path: str
23 :param field_storage: The :class:`FileStorage` instance to wrap
24 :type field_storage: FileStorage
25 :param temporary: Whether or not to delete the file when the File
26 instance is destructed
27 :type temporary: bool
28 :returns: A buffered writable file descriptor
29 :rtype: BufferedFileStorage
30
31 `reStructuredText`_ is great, but it creates visually dense, hard to read
32 :pep:`docstrings <287>`. Compare the jumble above to the same thing rewritten
33 according to the `Google Python Style Guide`_:
34
35 .. code-block:: text
36
37 Args:
38 path (str): The path of the file to wrap
39 field_storage (FileStorage): The :class:`FileStorage` instance to wrap
40 temporary (bool): Whether or not to delete the file when the File
41 instance is destructed
42
43 Returns:
44 BufferedFileStorage: A buffered writable file descriptor
45
46 Much more legible, no?
47
48 Napoleon is a :term:`extension` that enables Sphinx to parse both `NumPy`_ and
49 `Google`_ style docstrings - the style recommended by `Khan Academy`_.
50
51 Napoleon is a pre-processor that parses `NumPy`_ and `Google`_ style
52 docstrings and converts them to reStructuredText before Sphinx attempts to
53 parse them. This happens in an intermediate step while Sphinx is processing
54 the documentation, so it doesn't modify any of the docstrings in your actual
55 source code files.
56
57 .. _ReStructuredText: https://docutils.sourceforge.io/rst.html
58 .. _Google Python Style Guide:
59 https://google.github.io/styleguide/pyguide.html
60 .. _Google:
61 https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings
62 .. _NumPy:
63 https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard
64 .. _Khan Academy:
65 https://github.com/Khan/style-guides/blob/master/style/python.md#docstrings
66
67 Getting Started
68 ~~~~~~~~~~~~~~~
69
70 1. After :doc:`setting up Sphinx </usage/quickstart>` to build your docs,
71 enable napoleon in the Sphinx ``conf.py`` file:
72
73 .. code-block:: python
74
75 # conf.py
76
77 # Add napoleon to the extensions list
78 extensions = ['sphinx.ext.napoleon']
79
80 2. Use ``sphinx-apidoc`` to build your API documentation:
81
82 .. code-block:: console
83
84 $ sphinx-apidoc -f -o docs/source projectdir
85
86
87 Docstrings
88 ~~~~~~~~~~
89
90 Napoleon interprets every docstring that :mod:`autodoc <sphinx.ext.autodoc>`
91 can find, including docstrings on: ``modules``, ``classes``, ``attributes``,
92 ``methods``, ``functions``, and ``variables``. Inside each docstring,
93 specially formatted `Sections`_ are parsed and converted to
94 reStructuredText.
95
96 All standard reStructuredText formatting still works as expected.
97
98
99 .. _Sections:
100
101 Docstring Sections
102 ~~~~~~~~~~~~~~~~~~
103
104 All of the following section headers are supported:
105
106 * ``Args`` *(alias of Parameters)*
107 * ``Arguments`` *(alias of Parameters)*
108 * ``Attention``
109 * ``Attributes``
110 * ``Caution``
111 * ``Danger``
112 * ``Error``
113 * ``Example``
114 * ``Examples``
115 * ``Hint``
116 * ``Important``
117 * ``Keyword Args`` *(alias of Keyword Arguments)*
118 * ``Keyword Arguments``
119 * ``Methods``
120 * ``Note``
121 * ``Notes``
122 * ``Other Parameters``
123 * ``Parameters``
124 * ``Return`` *(alias of Returns)*
125 * ``Returns``
126 * ``Raise`` *(alias of Raises)*
127 * ``Raises``
128 * ``References``
129 * ``See Also``
130 * ``Tip``
131 * ``Todo``
132 * ``Warning``
133 * ``Warnings`` *(alias of Warning)*
134 * ``Warn`` *(alias of Warns)*
135 * ``Warns``
136 * ``Yield`` *(alias of Yields)*
137 * ``Yields``
138
139 Google vs NumPy
140 ~~~~~~~~~~~~~~~
141
142 Napoleon supports two styles of docstrings: `Google`_ and `NumPy`_. The
143 main difference between the two styles is that Google uses indentation to
144 separate sections, whereas NumPy uses underlines.
145
146 Google style:
147
148 .. code-block:: python
149
150 def func(arg1, arg2):
151 """Summary line.
152
153 Extended description of function.
154
155 Args:
156 arg1 (int): Description of arg1
157 arg2 (str): Description of arg2
158
159 Returns:
160 bool: Description of return value
161
162 """
163 return True
164
165 NumPy style:
166
167 .. code-block:: python
168
169 def func(arg1, arg2):
170 """Summary line.
171
172 Extended description of function.
173
174 Parameters
175 ----------
176 arg1 : int
177 Description of arg1
178 arg2 : str
179 Description of arg2
180
181 Returns
182 -------
183 bool
184 Description of return value
185
186 """
187 return True
188
189 NumPy style tends to require more vertical space, whereas Google style
190 tends to use more horizontal space. Google style tends to be easier to
191 read for short and simple docstrings, whereas NumPy style tends be easier
192 to read for long and in-depth docstrings.
193
194 The choice between styles is largely aesthetic, but the two styles should
195 not be mixed. Choose one style for your project and be consistent with it.
196
197 .. seealso::
198
199 For complete examples:
200
201 * :ref:`example_google`
202 * :ref:`example_numpy`
203
204
205 Type Annotations
206 ~~~~~~~~~~~~~~~~
207
208 :pep:`484` introduced a standard way to express types in Python code.
209 This is an alternative to expressing types directly in docstrings.
210 One benefit of expressing types according to :pep:`484` is that
211 type checkers and IDEs can take advantage of them for static code
212 analysis. :pep:`484` was then extended by :pep:`526` which introduced
213 a similar way to annotate variables (and attributes).
214
215 Google style with type annotations:
216
217 .. code-block:: python
218
219 def func(arg1: int, arg2: str) -> bool:
220 """Summary line.
221
222 Extended description of function.
223
224 Args:
225 arg1: Description of arg1
226 arg2: Description of arg2
227
228 Returns:
229 Description of return value
230
231 """
232 return True
233
234 class Class:
235 """Summary line.
236
237 Extended description of class
238
239 Attributes:
240 attr1: Description of attr1
241 attr2: Description of attr2
242 """
243
244 attr1: int
245 attr2: str
246
247 Google style with types in docstrings:
248
249 .. code-block:: python
250
251 def func(arg1, arg2):
252 """Summary line.
253
254 Extended description of function.
255
256 Args:
257 arg1 (int): Description of arg1
258 arg2 (str): Description of arg2
259
260 Returns:
261 bool: Description of return value
262
263 """
264 return True
265
266 class Class:
267 """Summary line.
268
269 Extended description of class
270
271 Attributes:
272 attr1 (int): Description of attr1
273 attr2 (str): Description of attr2
274 """
275
276
277 Configuration
278 -------------
279
280 Listed below are all the settings used by napoleon and their default
281 values. These settings can be changed in the Sphinx ``conf.py`` file. Make
282 sure that "sphinx.ext.napoleon" is enabled in ``conf.py``:
283
284 .. code-block:: python
285
286 # conf.py
287
288 # Add any Sphinx extension module names here, as strings
289 extensions = ['sphinx.ext.napoleon']
290
291 # Napoleon settings
292 napoleon_google_docstring = True
293 napoleon_numpy_docstring = True
294 napoleon_include_init_with_doc = False
295 napoleon_include_private_with_doc = False
296 napoleon_include_special_with_doc = True
297 napoleon_use_admonition_for_examples = False
298 napoleon_use_admonition_for_notes = False
299 napoleon_use_admonition_for_references = False
300 napoleon_use_ivar = False
301 napoleon_use_param = True
302 napoleon_use_rtype = True
303 napoleon_preprocess_types = False
304 napoleon_type_aliases = None
305 napoleon_attr_annotations = True
306
307 .. _Google style:
308 https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings
309 .. _NumPy style:
310 https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard
311
312 .. confval:: napoleon_google_docstring
313 :type: :code-py:`bool`
314 :default: :code-py:`True`
315
316 True to parse `Google style`_ docstrings. False to disable support
317 for Google style docstrings.
318
319 .. confval:: napoleon_numpy_docstring
320 :type: :code-py:`bool`
321 :default: :code-py:`True`
322
323 True to parse `NumPy style`_ docstrings. False to disable support
324 for NumPy style docstrings.
325
326 .. confval:: napoleon_include_init_with_doc
327 :type: :code-py:`bool`
328 :default: :code-py:`False`
329
330 True to list ``__init___`` docstrings separately from the class
331 docstring. False to fall back to Sphinx's default behavior, which
332 considers the ``__init___`` docstring as part of the class
333 documentation.
334
335 **If True**:
336
337 .. code-block:: python
338
339 def __init__(self):
340 """
341 This will be included in the docs because it has a docstring
342 """
343
344 def __init__(self):
345 # This will NOT be included in the docs
346
347 .. confval:: napoleon_include_private_with_doc
348 :type: :code-py:`bool`
349 :default: :code-py:`False`
350
351 True to include private members (like ``_membername``) with docstrings
352 in the documentation. False to fall back to Sphinx's default behavior.
353
354 **If True**:
355
356 .. code-block:: python
357
358 def _included(self):
359 """
360 This will be included in the docs because it has a docstring
361 """
362 pass
363
364 def _skipped(self):
365 # This will NOT be included in the docs
366 pass
367
368 .. confval:: napoleon_include_special_with_doc
369 :type: :code-py:`bool`
370 :default: :code-py:`True`
371
372 True to include special members (like ``__membername__``) with
373 docstrings in the documentation. False to fall back to Sphinx's
374 default behavior.
375
376 **If True**:
377
378 .. code-block:: python
379
380 def __str__(self):
381 """
382 This will be included in the docs because it has a docstring
383 """
384 return unicode(self).encode('utf-8')
385
386 def __unicode__(self):
387 # This will NOT be included in the docs
388 return unicode(self.__class__.__name__)
389
390 .. confval:: napoleon_use_admonition_for_examples
391 :type: :code-py:`bool`
392 :default: :code-py:`False`
393
394 True to use the ``.. admonition::`` directive for the **Example** and
395 **Examples** sections. False to use the ``.. rubric::`` directive
396 instead. One may look better than the other depending on what HTML
397 theme is used.
398
399 This `NumPy style`_ snippet will be converted as follows:
400
401 .. code-block:: text
402
403 Example
404 -------
405 This is just a quick example
406
407 **If True**:
408
409 .. code-block:: rst
410
411 .. admonition:: Example
412
413 This is just a quick example
414
415 **If False**:
416
417 .. code-block:: rst
418
419 .. rubric:: Example
420
421 This is just a quick example
422
423 .. confval:: napoleon_use_admonition_for_notes
424 :type: :code-py:`bool`
425 :default: :code-py:`False`
426
427 True to use the ``.. admonition::`` directive for **Notes** sections.
428 False to use the ``.. rubric::`` directive instead.
429
430 .. note:: The singular **Note** section will always be converted to a
431 ``.. note::`` directive.
432
433 .. seealso::
434
435 :confval:`napoleon_use_admonition_for_examples`
436
437 .. confval:: napoleon_use_admonition_for_references
438 :type: :code-py:`bool`
439 :default: :code-py:`False`
440
441 True to use the ``.. admonition::`` directive for **References**
442 sections. False to use the ``.. rubric::`` directive instead.
443
444 .. seealso::
445
446 :confval:`napoleon_use_admonition_for_examples`
447
448 .. confval:: napoleon_use_ivar
449 :type: :code-py:`bool`
450 :default: :code-py:`False`
451
452 True to use the ``:ivar:`` role for instance variables. False to use
453 the ``.. attribute::`` directive instead.
454
455 This `NumPy style`_ snippet will be converted as follows:
456
457 .. code-block:: text
458
459 Attributes
460 ----------
461 attr1 : int
462 Description of `attr1`
463
464 **If True**:
465
466 .. code-block:: rst
467
468 :ivar attr1: Description of `attr1`
469 :vartype attr1: int
470
471 **If False**:
472
473 .. code-block:: rst
474
475 .. attribute:: attr1
476
477 Description of `attr1`
478
479 :type: int
480
481 .. confval:: napoleon_use_param
482 :type: :code-py:`bool`
483 :default: :code-py:`True`
484
485 True to use a ``:param:`` role for each function parameter. False to
486 use a single ``:parameters:`` role for all the parameters.
487
488 This `NumPy style`_ snippet will be converted as follows:
489
490 .. code-block:: text
491
492 Parameters
493 ----------
494 arg1 : str
495 Description of `arg1`
496 arg2 : int, optional
497 Description of `arg2`, defaults to 0
498
499 **If True**:
500
501 .. code-block:: rst
502
503 :param arg1: Description of `arg1`
504 :type arg1: str
505 :param arg2: Description of `arg2`, defaults to 0
506 :type arg2: :class:`int`, *optional*
507
508 **If False**:
509
510 .. code-block:: rst
511
512 :parameters: * **arg1** (*str*) --
513 Description of `arg1`
514 * **arg2** (*int, optional*) --
515 Description of `arg2`, defaults to 0
516
517 .. confval:: napoleon_use_keyword
518 :type: :code-py:`bool`
519 :default: :code-py:`True`
520
521 True to use a ``:keyword:`` role for each function keyword argument.
522 False to use a single ``:keyword arguments:`` role for all the
523 keywords.
524
525 This behaves similarly to :confval:`napoleon_use_param`. Note unlike docutils,
526 ``:keyword:`` and ``:param:`` will not be treated the same way - there will
527 be a separate "Keyword Arguments" section, rendered in the same fashion as
528 "Parameters" section (type links created if possible)
529
530 .. seealso::
531
532 :confval:`napoleon_use_param`
533
534 .. confval:: napoleon_use_rtype
535 :type: :code-py:`bool`
536 :default: :code-py:`True`
537
538 True to use the ``:rtype:`` role for the return type. False to output
539 the return type inline with the description.
540
541 This `NumPy style`_ snippet will be converted as follows:
542
543 .. code-block:: text
544
545 Returns
546 -------
547 bool
548 True if successful, False otherwise
549
550 **If True**:
551
552 .. code-block:: rst
553
554 :returns: True if successful, False otherwise
555 :rtype: bool
556
557 **If False**:
558
559 .. code-block:: rst
560
561 :returns: *bool* -- True if successful, False otherwise
562
563 .. confval:: napoleon_preprocess_types
564 :type: :code-py:`bool`
565 :default: :code-py:`False`
566
567 True to convert the type definitions in the docstrings as references.
568
569 .. versionadded:: 3.2.1
570 .. versionchanged:: 3.5
571
572 Do preprocess the Google style docstrings also.
573
574 .. confval:: napoleon_type_aliases
575 :type: :code-py:`dict[str, str] | None`
576 :default: :code-py:`None`
577
578 A mapping to translate type names to other names or references. Works
579 only when ``napoleon_use_param = True``.
580
581 With:
582
583 .. code-block:: python
584
585 napoleon_type_aliases = {
586 "CustomType": "mypackage.CustomType",
587 "dict-like": ":term:`dict-like <mapping>`",
588 }
589
590 This `NumPy style`_ snippet:
591
592 .. code-block:: text
593
594 Parameters
595 ----------
596 arg1 : CustomType
597 Description of `arg1`
598 arg2 : dict-like
599 Description of `arg2`
600
601 becomes:
602
603 .. code-block:: rst
604
605 :param arg1: Description of `arg1`
606 :type arg1: mypackage.CustomType
607 :param arg2: Description of `arg2`
608 :type arg2: :term:`dict-like <mapping>`
609
610 .. versionadded:: 3.2
611
612 .. confval:: napoleon_attr_annotations
613 :type: :code-py:`bool`
614 :default: :code-py:`True`
615
616 True to allow using :pep:`526` attributes annotations in classes.
617 If an attribute is documented in the docstring without a type and
618 has an annotation in the class body, that type is used.
619
620 .. versionadded:: 3.4
621
622 .. confval:: napoleon_custom_sections
623 :type: :code-py:`Sequence[str | tuple[str, str]] | None`
624 :default: :code-py:`None`
625
626 Add a list of custom sections to include, expanding the list of parsed sections.
627
628 The entries can either be strings or tuples, depending on the intention:
629
630 * To create a custom "generic" section, just pass a string.
631 * To create an alias for an existing section, pass a tuple containing the
632 alias name and the original, in that order.
633 * To create a custom section that displays like the parameters or returns
634 section, pass a tuple containing the custom section name and a string
635 value, "params_style" or "returns_style".
636
637 If an entry is just a string, it is interpreted as a header for a generic
638 section. If the entry is a tuple/list/indexed container, the first entry
639 is the name of the section, the second is the section key to emulate. If the
640 second entry value is "params_style" or "returns_style", the custom section
641 will be displayed like the parameters section or returns section.
642
643 .. versionadded:: 1.8
644 .. versionchanged:: 3.5
645 Support ``params_style`` and ``returns_style``