Debian Codegraph @

docs/source/codedoc.rst

raw
1 How to Document Your Code
2 =========================
3
4
5 Docstrings
6 ----------
7
8 In Python, a string at the top of a module, class or function is called a *docstring*.
9 For example::
10
11 """This docstring describes the purpose of this module."""
12
13 class C:
14 """This docstring describes the purpose of this class."""
15
16 def m(self):
17 """This docstring describes the purpose of this method."""
18
19 Pydoctor also supports *attribute docstrings*::
20
21 CONST = 123
22 """This docstring describes a module level constant."""
23
24 class C:
25 cvar = None
26 """This docstring describes a class variable."""
27
28 def __init__(self):
29 self.ivar = []
30 """This docstring describes an instance variable."""
31
32 Attribute docstrings are not part of the Python language itself (`PEP 224 <https://www.python.org/dev/peps/pep-0224/>`_ was rejected), so these docstrings are not available at runtime.
33
34 For long docstrings, start with a short summary, followed by an empty line::
35
36 def f():
37 """This line is used as the summary.
38
39 More detail about the workings of this function can be added here.
40 They will be displayed in the documentation of the function itself
41 but omitted from the summary table.
42 """
43
44 Since docstrings are Python strings, escape sequences such as ``\n`` will be parsed as if the corresponding character---for example a newline---occurred at the position of the escape sequence in the source code.
45
46 To have the text ``\n`` in a docstring at runtime and in the generated documentation, you either have escape it twice in the source: ``\\n`` or use the ``r`` prefix for a raw string literal.
47 The following example shows the raw string approach::
48
49 def iter_lines(stream):
50 r"""Iterate through the lines in the given text stream,
51 with newline characters (\n) removed.
52 """
53 for line in stream:
54 yield line.rstrip('\n')
55
56 Further reading:
57
58 - `Python Tutorial: Documentation Strings <https://docs.python.org/3/tutorial/controlflow.html#documentation-strings>`_
59 - `PEP 257 -- Docstring Conventions <https://www.python.org/dev/peps/pep-0257/>`_
60 - `Python Language Reference: String and Bytes literals <https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals>`_
61
62
63 Docstring assignments
64 ---------------------
65
66 Simple assignments to the ``__doc__`` attribute of a class or function are recognized by pydoctor::
67
68 class CustomException(Exception):
69 __doc__ = MESSAGE = "Oops!"
70
71 Non-trivial assignments to ``__doc__`` are not supported. A warning will be logged by pydoctor as a reminder that the assignment will not be part of the generated API documentation::
72
73 if LOUD_DOCS:
74 f.__doc__ = f.__doc__.upper()
75
76 Assignments to ``__doc__`` inside functions are ignored by pydoctor. This can be used to avoid warnings when you want to modify runtime docstrings without affecting the generated API documentation::
77
78 def mark_unavailable(func):
79 func.__doc__ = func.__doc__ + '\n\nUnavailable on this system.'
80
81 if not is_supported('thing'):
82 mark_unavailable(do_the_thing)
83
84 Augmented assignments like ``+=`` are currently ignored as well, but that is an implementation limitation rather than a design decision, so this might change in the future.
85
86 Constants
87 ---------
88
89 The value of a constant is rendered with syntax highlighting.
90 See `module <docformat/restructuredtext/restructuredtext_demo.constants.html>`_ demonstrating the constant values rendering.
91
92 Following `PEP8 <https://www.python.org/dev/peps/pep-0008/#constants>`_, any variable defined with all upper case name will be considered as a constant.
93 Additionally, starting with Python 3.8, one can use the `typing.Final <https://www.python.org/dev/peps/pep-0008/#constants>`_ qualifier to declare a constant.
94
95 For instance, these variables will be recognized as constants::
96
97 from typing import Final
98 X = 3.14
99 y: Final = ['a', 'b']
100
101 In Python 3.6 and 3.7, you can use the qualifier present in the `typing_extensions` instead of `typing.Final`::
102
103 from typing_extensions import Final
104 z: Final = 'relative/path'
105
106 .. _codedoc-fields:
107
108 Fields
109 ------
110
111 Pydoctor supports most of the common fields usable in Sphinx, and some others.
112
113 Epytext fields are written with arobase, like ``@field:`` or ``@field arg:``.
114 ReStructuredText fields are written with colons, like ``:field:`` or ``:field arg:``.
115
116 Here are the supported fields (written with ReStructuredText format, but same fields are supported with Epytext):
117
118 - ``:cvar foo:``, document a class variable named ``foo``. Applicable in the context of the docstring of a class.
119 - ``:ivar foo:``, document a instance variable named ``foo``. Applicable in the context of the docstring of a class.
120 - ``:var foo:``, document a variable named ``foo``. Applicable in the context of the docstring of a module or class.
121 If used in the context of a class, behaves just like ``@ivar:``.
122 - ``:note:``, add a note section.
123 - ``:param bar:`` (synonym: ``@arg bar:``), document a function's (or method's) parameter named ``bar``.
124 Applicable in the context of the docstring of a function of method.
125 - ``:keyword:``, document a function's (or method's) keyword parameter (``**kwargs``).
126 - ``:type bar: C{list}``, document the type of an argument/keyword or variable (``bar`` in this example), depending on the context.
127 - ``:return:`` (synonym: ``@returns:``), document the return type of a function (or method).
128 - ``:rtype:`` (synonym: ``@returntype:``), document the type of the return value of a function (or method).
129 - ``:yield:`` (synonym: ``@yields:``), document the values yielded by a generator function (or method).
130 - ``:ytype:`` (synonym: ``@yieldtype:``), document the type of the values yielded by a generator function (or method).
131 - ``:raise ValueError:`` (synonym: ``@raises ValueError:``), document the potential exception a function (or method) can raise.
132 - ``:warn RuntimeWarning:`` (synonym: ``@warns ValueError:``), document the potential warning a function (or method) can trigger.
133 - ``:see:`` (synonym: ``@seealso:``), add a see also section.
134 - ``:since:``, document the date and/or version since a component is present in the API.
135 - ``:author:``, document the author of a component, generally a module.
136
137 .. note:: Currently, any other fields will be considered "unknown" and will be flagged as such.
138 See `"fields" issues <https://github.com/twisted/pydoctor/issues?q=is%3Aissue+is%3Aopen+fields>`_
139 for discussions and improvements.
140
141 .. note:: Unlike Sphinx, ``vartype`` and ``kwtype`` are not recognized as valid fields, we simply use ``type`` everywhere.
142
143 Type fields
144 ~~~~~~~~~~~
145
146 Type fields, namely ``type``, ``rtype`` and ``ytype``, can be interpreted, such that, instead of being just a regular text field,
147 types can be linked automatically.
148 For reStructuredText and Epytext documentation format, enable this behaviour with the option::
149
150 --process-types
151
152 The type auto-linking is always enabled for Numpy and Google style documentation formats.
153
154 Like in Sphinx, regular types and container types such as lists and dictionaries can be linked automatically::
155
156 :type priority: int
157 :type priorities: list[int]
158 :type mapping: dict(str, int)
159 :type point: tuple[float, float]
160
161 Natural language types can be linked automatically if separated by the words “or”, "and", "to", "of" or the comma::
162
163 :rtype: float or str
164 :returntype: list of str or list[int]
165 :ytype: tuple of str, int and float
166 :yieldtype: mapping of str to int
167
168 Additionally, it's still possible to include regular text description inside a type specification::
169
170 :rtype: a result that needs a longer text description or str
171 :rtype: tuple of a result that
172 needs a longer text description and str
173
174 Some special keywords will be recognized: "optional" and "default"::
175
176 :type value: list[float], optional
177 :type value: int, default: -1
178 :type value: dict(str, int), default: same as default_dict
179
180 .. note:: Literals caracters - numbers and strings within quotes - will be automatically rendered like docutils literals.
181
182 .. note:: It's not currently possible to combine parameter type and description inside the same ``param`` field, see issue `#267 <https://github.com/twisted/pydoctor/issues/267>`_.
183
184 Type annotations
185 ----------------
186
187 Type annotations in your source code will be included in the API documentation that pydoctor generates.
188 For example::
189
190 colors: dict[str, int] = {
191 'red': 0xFF0000, 'green': 0x00FF00, 'blue': 0x0000FF
192 }
193
194 def inverse(name: str) -> int:
195 return colors[name] ^ 0xFFFFFF
196
197 If your project still supports Python versions prior to 3.6, you can also use type comments::
198
199 from typing import Optional
200
201 favorite_color = None # type: Optional[str]
202
203 However, the ability to extract type comments only exists in the parser of Python 3.8 and later, so make sure you run pydoctor using a recent Python version, or the type comments will be ignored.
204
205 There is basic type inference support for variables/constants that are assigned literal values.
206 Unlike for example mypy, pydoctor cannot infer the type for computed values::
207
208 FIBONACCI = [1, 1, 2, 3, 5, 8, 13]
209 # pydoctor will automatically determine the type: list[int]
210
211 SQUARES = [n ** 2 for n in range(10)]
212 # pydoctor needs an annotation to document this type
213
214 Type variables and type aliases will be recognized as such and their value will be colorized in HTML::
215
216 from typing import Callable, Tuple, TypeAlias, TypeVar
217 T = TypeVar('T') # a type variable
218 Parser = Callable[[str], Tuple[int, bytes, bytes]] # a type alias
219
220 .. note:: About name resolving in annotations:
221 ``pydoctor`` checks for top-level names first before checking for other names,
222 this is true only for annotations.
223
224 This behaviour matches pyright's when PEP-563 is enabled
225 (module starts with ``from __future__ import annotations``).
226
227 When there is an ambiguous annotation, a warning can be printed if option ``-v`` is supplied.
228
229 Further reading:
230
231 - `Python Standard Library: typing -- Support for type hints <https://docs.python.org/3/library/typing.html>`_
232 - `PEP 483 -- The Theory of Type Hints <https://www.python.org/dev/peps/pep-0483/>`_
233 - `PEP 563 -- Postponed Evaluation of Annotations <https://www.python.org/dev/peps/pep-0563/>`_
234
235 Properties
236 ----------
237
238 A method with a decoration ending in ``property`` or ``Property`` will be included in the generated API documentation as an attribute rather than a method::
239
240 class Knight:
241
242 @property
243 def name(self):
244 return self._name
245
246 @abc.abstractproperty
247 def age(self):
248 raise NotImplementedError
249
250 @customProperty
251 def quest(self):
252 return f'Find the {self._object}'
253
254 All you have to do for pydoctor to recognize your custom properties is stick to this naming convention.
255
256
257 Using ``attrs``
258 ---------------
259
260 If you use the ``attrs`` library to define attributes on your classes, you can use inline docstrings combined with type annotations to provide pydoctor with all the information it needs to document those attributes::
261
262 import attr
263
264 @attr.s(auto_attribs=True)
265 class SomeClass:
266
267 a_number: int = 42
268 """One number."""
269
270 list_of_numbers: list[int]
271 """Multiple numbers."""
272
273 If you are using explicit ``attr.ib`` definitions instead of ``auto_attribs``, pydoctor will try to infer the type of the attribute from the default value, but will need help in the form of type annotations or comments for collections and custom types::
274
275 from typing import List
276 import attr
277
278 @attr.s
279 class SomeClass:
280
281 a_number = attr.ib(default=42)
282 """One number."""
283
284 list_of_numbers = attr.ib(factory=list) # type: List[int]
285 """Multiple numbers."""
286
287
288 Private API
289 -----------
290
291 Modules, classes and functions of which the name starts with an underscore are considered *private*. These will not be shown by default, but there is a button in the generated documentation to reveal them. An exception to this rule is *dunders*: names that start and end with double underscores, like ``__str__`` and ``__eq__``, which are always considered public::
292
293 class _Private:
294 """This class won't be shown unless explicitly revealed."""
295
296 class Public:
297 """This class is public, but some of its methods are private."""
298
299 def public(self):
300 """This is a public method."""
301
302 def _private(self):
303 """For internal use only."""
304
305 def __eq__(self, other):
306 """Is this object equal to 'other'?
307
308 This method is public.
309 """
310
311 .. note::
312 Pydoctor actually supports 3 types of privacy: public, private and hidden.
313 See :ref:`Override objects privacy <customize-privacy>` for more informations.
314
315 Re-exporting
316 ------------
317
318 If your project is a library or framework of significant size, you might want to split the implementation over multiple private modules while keeping the public API importable from a single module. This is supported using pydoctor's re-export feature.
319
320 A documented element which is defined in one (typically private) module can be imported into another module and re-exported by naming it in the ``__all__`` special variable. Doing so will move its documentation to the module from where it was re-exported, which is where users of your project will be importing it from.
321
322 In the following example, the documentation of ``MyClass`` is written in the ``my_project.core._impl`` module, which is imported into the top-level ``__init__.py`` and then re-exported by including ``"MyClass"`` in the value of ``__all__``. As a result, the documentation for ``MyClass`` can be read in the documentation of the top-level ``my_project`` package::
323
324 ├── README.rst
325 ├── my_project
326 │ ├── __init__.py <-- Re-exports my_project.core._impl.MyClass
327 │ ├── core as my_project.MyClass
328 │ │ ├── __init__.py
329 │ │ ├── _impl.py <-- Defines and documents MyClass
330
331 The content of ``my_project/__init__.py`` includes::
332
333 from .core._impl import MyClass
334
335 __all__ = ("MyClass",)
336
337 Branch priorities
338 -----------------
339
340 When pydoctor deals with try/except/else or if/else block, it makes sure that the names defined in
341 the main flow has precedence over the definitions in ``except`` handlers or ``else`` blocks.
342
343 Meaning that in the context of the code below, ``ssl`` would resolve to ``twisted.internet.ssl``:
344
345 .. code:: python
346
347 try:
348 # main flow
349 from twisted.internet import ssl as _ssl
350 except ImportError:
351 # exceptional flow
352 ssl = None # ignored since 'ssl' is defined in the main flow below.
353 var = True # not ignored since 'var' is not defined anywhere else.
354 else:
355 # main flow
356 ssl = _ssl
357
358 Similarly, in the context of the code below, the ``CapSys`` protocol under the ``TYPE_CHECKING`` block will be
359 documented and the runtime version will be ignored.
360
361 .. code:: python
362
363 from typing import TYPE_CHECKING
364 if TYPE_CHECKING:
365 # main flow
366 from typing import Protocol
367 class CapSys(Protocol):
368 def readouterr() -> Any:
369 ...
370 else:
371 # secondary flow
372 class CapSys(object): # ignored since 'CapSys' is defined in the main flow above.
373 ...
374
375 But sometimes pydoctor can be better off analysing the ``TYPE_CHECKING`` blocks and should
376 stick to the runtime version of the code instead.
377 For these case, you might want to inverse the condition of if statement:
378
379 .. code:: python
380
381 if not TYPE_CHECKING:
382 # main flow
383 from ._implementation import Thing
384 else:
385 # secondary flow
386 from ._typing import Thing # ignored since 'Thing' is defined in the main flow above.