Debian Codegraph @

doc/tutorial/describing-code.rst

raw
1 Describing code in Sphinx
2 =========================
3
4 In the :doc:`previous sections of the tutorial </tutorial/index>` you can read
5 how to write narrative or prose documentation in Sphinx. In this section you
6 will describe code objects instead.
7
8 Sphinx supports documenting code objects in several languages, namely Python,
9 C, C++, JavaScript, and reStructuredText. Each of them can be documented using
10 a series of directives and roles grouped by
11 :doc:`domain </usage/domains/index>`. For the remainder of the
12 tutorial you will use the Python domain, but all the concepts seen in this
13 section apply for the other domains as well.
14
15 .. _tutorial-describing-objects:
16
17 Python
18 ------
19
20 Documenting Python objects
21 ~~~~~~~~~~~~~~~~~~~~~~~~~~
22
23 Sphinx offers several roles and directives to document Python objects,
24 all grouped together in :doc:`the Python domain </usage/domains/python>`.
25 For example, you can use the :rst:dir:`py:function` directive to document
26 a Python function, as follows:
27
28 .. code-block:: rst
29 :caption: docs/source/usage.rst
30
31 Creating recipes
32 ----------------
33
34 To retrieve a list of random ingredients,
35 you can use the ``lumache.get_random_ingredients()`` function:
36
37 .. py:function:: lumache.get_random_ingredients(kind=None)
38
39 Return a list of random ingredients as strings.
40
41 :param kind: Optional "kind" of ingredients.
42 :type kind: list[str] or None
43 :return: The ingredients list.
44 :rtype: list[str]
45
46 Which will render like this:
47
48 .. figure:: /_static/tutorial/lumache-py-function.png
49 :width: 80%
50 :align: center
51 :alt: HTML result of documenting a Python function in Sphinx
52
53 The rendered result of documenting a Python function in Sphinx
54
55 Notice several things:
56
57 - Sphinx parsed the argument of the ``.. py:function`` directive and
58 highlighted the module, the function name, and the parameters appropriately.
59 - The directive content includes a one-line description of the function,
60 as well as an :ref:`info field list <info-field-lists>` containing the function
61 parameter, its expected type, the return value, and the return type.
62
63 .. note::
64
65 The ``py:`` prefix specifies the :term:`domain`. You may configure the
66 default domain so you can omit the prefix, either globally using the
67 :confval:`primary_domain` configuration, or use the
68 :rst:dir:`default-domain` directive to change it from the point it is called
69 until the end of the file.
70 For example, if you set it to ``py`` (the default), you can write
71 ``.. function::`` directly.
72
73 Cross-referencing Python objects
74 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
75
76 By default, most of these directives generate entities that can be
77 cross-referenced from any part of the documentation by using
78 :ref:`a corresponding role <python-xref-roles>`. For the case of functions,
79 you can use :rst:role:`py:func` for that, as follows:
80
81 .. code-block:: rst
82 :caption: docs/source/usage.rst
83
84 The ``kind`` parameter should be either ``"meat"``, ``"fish"``,
85 or ``"veggies"``. Otherwise, :py:func:`lumache.get_random_ingredients`
86 will raise an exception.
87
88 When generating code documentation, Sphinx will generate a
89 cross-reference automatically just by using the name of the object,
90 without you having to explicitly use a role for that. For example, you
91 can describe the custom exception raised by the function using the
92 :rst:dir:`py:exception` directive:
93
94 .. code-block:: rst
95 :caption: docs/source/usage.rst
96
97 .. py:exception:: lumache.InvalidKindError
98
99 Raised if the kind is invalid.
100
101 Then, add this exception to the original description of the function:
102
103 .. code-block:: rst
104 :caption: docs/source/usage.rst
105 :emphasize-lines: 7
106
107 .. py:function:: lumache.get_random_ingredients(kind=None)
108
109 Return a list of random ingredients as strings.
110
111 :param kind: Optional "kind" of ingredients.
112 :type kind: list[str] or None
113 :raise lumache.InvalidKindError: If the kind is invalid.
114 :return: The ingredients list.
115 :rtype: list[str]
116
117 And finally, this is how the result would look:
118
119 .. figure:: /_static/tutorial/lumache-py-function-full.png
120 :width: 80%
121 :align: center
122 :alt: HTML result of documenting a Python function in Sphinx
123 with cross-references
124
125 HTML result of documenting a Python function in Sphinx with cross-references
126
127 Beautiful, isn't it?
128
129 Including doctests in your documentation
130 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
131
132 Since you are now describing code from a Python library, it will become useful
133 to keep both the documentation and the code as synchronized as possible.
134 One of the ways to do that in Sphinx is to include code snippets in the
135 documentation, called *doctests*, that are executed when the documentation is
136 built.
137
138 To demonstrate doctests and other Sphinx features covered in this tutorial,
139 Sphinx will need to be able to import the code. To achieve that, write this
140 at the beginning of ``conf.py``:
141
142 .. code-block:: python
143 :caption: docs/source/conf.py
144 :emphasize-lines: 3-5
145
146 # If extensions (or modules to document with autodoc) are in another directory,
147 # add these directories to sys.path here.
148 import sys
149 from pathlib import Path
150 sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
151
152 .. note::
153
154 An alternative to changing the :py:data:`sys.path` variable is to create a
155 ``pyproject.toml`` file and make the code installable,
156 so it behaves like any other Python library. However, the ``sys.path``
157 approach is simpler.
158
159 Then, before adding doctests to your documentation, enable the
160 :doc:`doctest </usage/extensions/doctest>` extension in ``conf.py``:
161
162 .. code-block:: python
163 :caption: docs/source/conf.py
164 :emphasize-lines: 3
165
166 extensions = [
167 'sphinx.ext.duration',
168 'sphinx.ext.doctest',
169 ]
170
171 Next, write a doctest block as follows:
172
173 .. code-block:: rst
174 :caption: docs/source/usage.rst
175
176 >>> import lumache
177 >>> lumache.get_random_ingredients()
178 ['shells', 'gorgonzola', 'parsley']
179
180 Doctests include the Python instructions to be run preceded by ``>>>``,
181 the standard Python interpreter prompt, as well as the expected output
182 of each instruction. This way, Sphinx can check whether the actual output
183 matches the expected one.
184
185 To observe how a doctest failure looks like (rather than a code error as
186 above), let's write the return value incorrectly first. Therefore, add a
187 function ``get_random_ingredients`` like this:
188
189 .. code-block:: python
190 :caption: lumache.py
191
192 def get_random_ingredients(kind=None):
193 return ["eggs", "bacon", "spam"]
194
195 You can now run ``make doctest`` to execute the doctests of your documentation.
196 Initially this will display an error, since the actual code does not behave
197 as specified:
198
199 .. code-block:: console
200
201 (.venv) $ make doctest
202 Running Sphinx v4.2.0
203 loading pickled environment... done
204 ...
205 running tests...
206
207 Document: usage
208 ---------------
209 **********************************************************************
210 File "usage.rst", line 44, in default
211 Failed example:
212 lumache.get_random_ingredients()
213 Expected:
214 ['shells', 'gorgonzola', 'parsley']
215 Got:
216 ['eggs', 'bacon', 'spam']
217 **********************************************************************
218 ...
219 make: *** [Makefile:20: doctest] Error 1
220
221 As you can see, doctest reports the expected and the actual results,
222 for easy examination. It is now time to fix the function:
223
224 .. code-block:: python
225 :caption: lumache.py
226 :emphasize-lines: 2
227
228 def get_random_ingredients(kind=None):
229 return ["shells", "gorgonzola", "parsley"]
230
231 And finally, ``make doctest`` reports success!
232
233 For big projects though, this manual approach can become a bit tedious.
234 In the next section, you will see :doc:`how to automate the
235 process </tutorial/automatic-doc-generation>`.
236
237 Other languages (C, C++, others)
238 --------------------------------
239
240 Documenting and cross-referencing objects
241 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
242
243 Sphinx also supports documenting and cross-referencing objects written in
244 other programming languages. There are four additional built-in domains:
245 C, C++, JavaScript, and reStructuredText. Third-party extensions may
246 define domains for more languages, such as
247
248 - `Fortran <https://sphinx-fortran.readthedocs.io>`_,
249 - `Julia <https://bastikr.github.io/sphinx-julia>`_, or
250 - `PHP <https://github.com/markstory/sphinxcontrib-phpdomain>`_.
251
252 For example, to document a C++ type definition, you would use the built-in
253 :rst:dir:`cpp:type` directive, as follows:
254
255 .. code-block:: rst
256
257 .. cpp:type:: std::vector<int> CustomList
258
259 A typedef-like declaration of a type.
260
261 Which would give the following result:
262
263 .. cpp:type:: std::vector<int> CustomList
264
265 A typedef-like declaration of a type.
266
267 All such directives then generate references that can be
268 cross-referenced by using the corresponding role. For example, to reference
269 the previous type definition, you can use the :rst:role:`cpp:type` role
270 as follows:
271
272 .. code-block:: rst
273
274 Cross reference to :cpp:type:`CustomList`.
275
276 Which would produce a hyperlink to the previous definition: :cpp:type:`CustomList`.