Debian Codegraph @

docs/guide/users/recommendations/docstrings.md

raw symbols SCIP
1 # Docstrings
2
3 Here are explanations on what docstrings are, and a few recommendations on how to write them. This guide uses the [Google-style](../../../reference/docstrings.md#google-style), because that is our preferred and recommended style, but you can also use any other supported style. Skip to the [Styles](#styles) section to learn about the existing docstring styles. We invite you to read their own style guides as they are full of examples and good advice.
4
5 ## Definition
6
7 A docstring is a line or block of text describing objects such as modules, classes, functions, attributes and type aliases. They are written below the object signature or assignment, or appear as first expression in a module:
8
9 ```python title="module.py"
10 """This is the module docstring."""
11
12 type X = dict[str, int]
13 """This is a type alias docstring."""
14
15 a = 0
16 """This is an attribute docstring."""
17
18
19 def b():
20 """This is a function docstring."""
21
22
23 class C:
24 """This is a class docstring."""
25
26 def d(self):
27 """This is a method docstring."""
28 ```
29
30 ## Multi-line docstrings
31
32 Each docstring can span multiple lines if it is wrapped in triple double-quotes (which is generally the case and the official recommendation even for single-line docstrings):
33
34 ```python
35 def function():
36 """This is a longer docstring.
37
38 It spans on multiple lines.
39 Blank lines are allowed, too.
40 """
41 ```
42
43 When writing multi-line docstrings, it is recommended to write a short description on the first line, then separate the rest of the docstring with a blank line. The first line is called the **summary**, and the rest of docstring is called the **body**. The summary is useful to documentation generators and other tools to show the short description of an object.
44
45 ## Markup
46
47 Docstrings are just text, so you can use any markup you want. The markup you choose will generally depend on what you decide to do with your docstrings: if you generate API documentation from your docstrings, and the documentation renderer expects Markdown, then you should write your docstrings in Markdown.
48
49 Examples of markups are [Markdown](https://daringfireball.net/projects/markdown/) (which has many different implementations and many different "flavors"), [reStructuredText](https://docutils.sourceforge.io/rst.html), [AsciiDoc](https://asciidoc.org/), and [Djot](https://djot.net/).
50
51 For example, if you are using [MkDocs](https://www.mkdocs.org) and [mkdocstrings](https://mkdocstrings.github.io/) to generate your API documentation, you should write your docstrings in Markdown. If you are using [Sphinx](https://www.sphinx-doc.org/en/master/), you should probably write your docstrings in reStructuredText, unless you are also using the [MyST](https://myst-parser.readthedocs.io/en/latest/index.html) extension.
52
53 Whatever markup you choose, try to stay consistent within your code base.
54
55 ## Styles
56
57 Docstrings can be written for modules, classes, functions, attributes, and type aliases. But there are other aspects of a Python API that need to be documented, such as function parameters, returned values, and raised exceptions, to name a few. We could document everything in natural language, but that would make it hard for downstream tools such as documentation generators to extract information in a structured way, to allow dedicated rendering such as tables for parameters.
58
59 To compensate for the lack of structure in natural languages, docstring "styles" emerged. A docstring style is a micro-format for docstrings, allowing to structure the information by following a specific format. With the most popular Google and Numpydoc styles, information in docstrings is decomposed into **sections** of different kinds, for example "parameter" sections or "return" sections. Some kinds of section then support documenting multiple items, or support a single block of markup. For example, we can document multiple parameters in "parameter" sections, but a "note" section is only composed of a text block.
60
61 Structuring the information in sections and items allows documentation-related tools to extract and provide this information in a structured way, by parsing the docstrings according to the style they follow. Griffe has parsers for [Google-style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings), [Numpydoc-style](https://numpydoc.readthedocs.io/en/latest/format.html), and [Sphinx-style](https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html) docstrings. See the complete reference for these parsers and styles in the [Docstrings reference](../../../reference/docstrings.md). We recommend that you read the style guides mentioned here as they are full of examples and good advice too.
62
63 <div class="grid cards" markdown>
64 <div markdown>
65
66 ```python title="Google-style"
67 def greet(name: str, end: str = "!") -> None:
68 """Greet someone.
69
70 Parameters:
71 name: The name to greet.
72 end: The punctuation mark at the end.
73
74 Note:
75 Greetings are cool!
76 """
77 print(f"Hey {name}{end}")
78
79
80
81 ‎
82 ```
83
84 <!-- The invisible character above is here on purpose, to make both divs the same height. -->
85
86 </div>
87 <div markdown>
88
89 ```python title="Numpydoc-style"
90 def greet(name: str, end: str = "!") -> None:
91 """Greet someone.
92
93 Parameters
94 ----------
95 name
96 The name to greet.
97 end
98 The punctuation mark at the end.
99
100 Note
101 ----
102 Greetings are cool!
103 """
104 print(f"Hey {name}{end}")
105 ```
106
107 </div>
108 </div>
109
110 Our preferred style for docstrings is the **Google-style**, because it is in our opinion the most markup-agnostic style: it is based on any kind of markup or documentation generator. Our second choice would be the Numpydoc-style, for its readability.
111
112 For the adventurers, have a look at [PEP 727](https://peps.python.org/pep-0727/) (draft) and [griffe-typingdoc](https://mkdocstrings.github.io/griffe-typingdoc/), a Griffe extension to support PEP 727. PEP 727 proposes an alternative way to provide information in a structured way, that does not rely on a docstring micro-format. It takes advantage of `typing.Annotated` to attach documentation to any type-annotated object, like attributes, parameters and returned values. With PEP 727, docstrings styles and their sections aren't required anymore, and docstrings can be written in plain markup, without following any particular style. This makes it easier for tools like Griffe who then don't have to parse docstrings *at all*. The PEP is a bit controversial (lots of different opinions), so we invite you to make your own opinion by looking at real-world projects using it, such as [FastAPI](https://github.com/tiangolo/fastapi/blob/master/fastapi/applications.py), or by reading the (very-long) [discussion on discuss.python.org](https://discuss.python.org/t/pep-727-documentation-metadata-in-typing/32566/17). The PEP was actually written by FastAPI's author, Sebastián Ramírez.
113
114 ```python title="PEP 727"
115 from typing_extensions import Annotated, Doc
116
117
118 def greet(
119 name: Annotated[str, Doc("The name to greet."),
120 end: Annotated[str, Doc("The punctuation mark at the end.")] = "!",
121 ) -> None:
122 """Greet someone.
123
124 > [!NOTE]
125 > Greetings are cool!
126 """ # (1)!
127 print(f"Hey {name}{end}")
128 ```
129
130 1. Here we use the [GitHub syntax](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts) for a "note" callout. It assumes our documentation renderer supports this syntax. The point is that we rely purely on Markdown rather than docstrings styles.
131
132 ## General tips
133
134 Your docstrings will typically be used to document your API, either on a deployed (static) website, or locally, on the command line or in a Python interpreter. Therefore, when writing your docstrings, you should address the right audience: the users of your code. Try to stay succinct and give clear examples. Docstrings are not really the place to explain architectural or technical decisions made while developing the project: this information, while extremely valuable, is better written in *code comments*, where the audience is other developers working on the code base.
135
136 Your docstrings will typically again be read online (HTML) or other types of documents such as manual pages or PDFs. Make sure to write complete sentences, with correct punctuation. That means for example, to start each parameter description with a capital letter, and to end it with a period.
137
138 When documenting objects acting as namespaces (modules, classes, enumerations), prefer documenting each attribute separately than with an Attributes section in the namespace object docstring. For example, add a docstring to each enumeration value rather than describing each value in the docstring of the enumeration class.
139
140 ## Modules
141
142 Module docstrings should briefly explain what the module contains, and for what purposes these objects can be used. If the documentation generator you chose does not support generating member summaries automatically, you might want to add docstrings sections for attributes, functions, classes, type aliases and submodules.
143
144 ```python title="package/__init__.py"
145 """A generic package to demonstrate docstrings.
146
147 This package does not really exist, and is only used as a demonstration purpose for docstrings.
148 Anyway, this package contains the following API, exposed directly at the top-level,
149 meaning you can import everything from `package` directly.
150
151 Attributes:
152 ghost: A ghost wandering in this desolated land.
153 dummy: A dummy you can practice on. Not for ghosts.
154
155 Classes:
156 Ghost: Ah, so this is where our ghost comes from.
157 Maybe create some additional ghosts so they can pass the time together?
158
159 Functions:
160 deploy(): Deploy something on the web (we're not sure what exactly).
161 """
162 ```
163
164 Do the same thing for every other module of the package, except if you are [hiding your module layout](public-apis.md#module-layout).
165
166 ## Classes, methods, properties
167
168 Class docstrings follow the same logic as module docstrings. Explain what the class is used for, and maybe show a few of its attributes and methods thanks to sections of the same name. A class is already more concrete than a module, so we can maybe start adding usage examples too. Such examples should only show how to create instances of the class. Examples of use for methods can be written in each respective method.
169
170 ```python
171 class Ghost:
172 """Ghosts that wander the earth.
173
174 Ghosts are meant to... we're actually unsure.
175 All we know is that, as a user, you might find it amusing to instantiate
176 a few of them and put them together to see what they do.
177
178 Methods:
179 wander: Wander the earth.
180 spook: Spook living organisms.
181 pass_through: Pass through anything.
182
183 Examples:
184 Create a new ghost with a cool nickname:
185
186 >>> ghost = Ghost(nickname="Rattlesnake")
187 """
188
189 def wander(self) -> None:
190 """Wander the earth.
191
192 That's it, really.
193
194 Examples:
195 >>> ghost.wander()
196 """
197 ...
198
199 @property
200 def weight(self) -> int:
201 """The ghost's weight (spoiler: it's close to 0)."""
202 ...
203 ```
204
205 Note that blocks of lines starting with `>>>` or `...` are automatically parsed as code blocks by Griffe, until a blank line is found. This only works in Examples (plural!) sections. If you rely on [Python-Markdown](https://python-markdown.github.io/) to convert Markdown to HTML (which is the case for MkDocs), you can use the [markdown-pycon](https://pawamoy.github.io/markdown-pycon/) extension to recognize such `pycon` code blocks anywhere, without having to wrap them in fences. You can also choose to use explicit fences everywhere:
206
207 ````python
208 """
209 Examples:
210 Create a new ghost with a cool nickname:
211
212 ```pycon
213 >>> ghost = Ghost(nickname="Rattlesnake")
214 ```
215 """
216 ````
217
218 ## Functions
219
220 Function and method docstrings will typically describe their parameters and return values. For generators, it's also possible to describe what the generator yields and what it can receive, though the latter is not often used.
221
222 ```python
223 import datetime
224 from typing import Generator, Iterator
225
226
227 class GhostOlympicGames:
228 ...
229
230
231 class GOGTicket:
232 ...
233
234
235 def organize_gog(date: datetime.date) -> GhostOlympicGames:
236 """Organize Olympic Games for Ghosts.
237
238 The ghost world is much simpler than the living world,
239 so it's super easy to organize big events like this.
240
241 Parameters:
242 date: The date of the games.
243
244 Returns:
245 The prepared games.
246 """
247 ...
248
249
250 def yield_athletes(quantity: int) -> Iterator[Ghost]:
251 """Yield a certain quantity of athletes.
252
253 Parameters:
254 quantity: How many ghost athletes you want.
255
256 Yields:
257 Ghost athletes. They're just regular ghosts.
258 """
259 ...
260
261
262
263 def gog_tickets_factory() -> Generator[GOGTicket, int, None]:
264 """Generate tickets for the GOG.
265
266 We value fairness: tickets are priced randomly.
267 Unless we send a specific price to the generator.
268
269 Yields:
270 Tickets for the games.
271
272 Receives:
273 Price for the next ticket, in ghost money (???).
274 """
275 ...
276 ```
277
278 ## Attributes
279
280 Attribute docstrings are written below their assignment. As usual, they should have a short summary, and an optional, longer body.
281
282 ```python
283 GHOST_MASS_CONSTANT: float = 1e-100
284 """The ghost mass constant.
285
286 This is a very small number. Use it scientifically
287 for all ghost-related things.
288
289 Note:
290 There is actually nothing scientific about any of this.
291 """ # (1)!
292 ```
293
294 1. Our `Note` section here is parsed as an admonition. See [Google-style admonitions](../../../reference/docstrings.md#google-admonitions) for reference.
295
296 Class and instance attributes can be documented the same way:
297
298 ```python
299 class GhostTown:
300 instances: str
301 """All the existing towns."""
302
303 def __init__(self, name: str, size: int) -> None:
304 self.name = name
305 """The town's name."""
306
307 self.size = size
308 """The town's size."""
309 ```
310
311 ## Type aliases
312
313 Type alias docstrings are written below their assignment. As usual, they should have a short summary, and an optional, longer body.
314
315 ```python
316 type Callback = typing.Callable[[int, str], typing.Any]
317 """Callback type for Frobnicators.
318
319 The first argument is the number of rounds to run, the second argument
320 is the name of the widget being frobnicated.
321 """
322 ```
323
324 ## Exceptions, warnings
325
326 Callables that raise exceptions or emit warnings can document each of these exceptions and warnings. Documenting them informs your users that they could or should catch the raised exceptions, or that they could filter or configure warnings differently. The description next to each exception or warning should explain how or when they are raised or emitted.
327
328 ```python
329 def verify_spirit_chest():
330 """Do a verification routine on the spirit chest.
331
332 Raises:
333 OverflowError: When the verification failed
334 and all the ghosts escaped from the spirit chest.
335 """
336 ...
337
338
339 def negotiate_return_to_the_spirit_chest():
340 """Negotiate with ghost for them to return in the spirit chest.
341
342 Warns:
343 ResourceWarning: When the ghosts refuse to go back in the chest
344 because the chest is too tight.
345 """
346 ...
347 ```
348
349 ## Going further
350
351 There are more sections and more features to discover and use. For a complete reference on docstring styles syntax, see our [reference](../../../reference/docstrings.md).