Debian Codegraph @

docs/peps/pep-0257.rst

raw
1 PEP: 257
2 Title: Docstring Conventions
3 Version: $Revision: 9906 $
4 Last-Modified: $Date: 2024-08-15 10:43:38 +0200 (Do, 15. Aug 2024) $
5 Authors: David Goodger <[email protected]>,
6 Guido van Rossum <[email protected]>
7 Discussions-To: [email protected]
8 Status: Active
9 Type: Informational
10 Content-Type: text/x-rst
11 Created: 29-May-2001
12 Post-History: 13-Jun-2001
13
14
15 Abstract
16 ========
17
18 This PEP documents the semantics and conventions associated with
19 Python docstrings.
20
21
22 Rationale
23 =========
24
25 The aim of this PEP is to standardize the high-level structure of
26 docstrings: what they should contain, and how to say it (without
27 touching on any markup syntax within docstrings). The PEP contains
28 conventions, not laws or syntax.
29
30 "A universal convention supplies all of maintainability, clarity,
31 consistency, and a foundation for good programming habits too.
32 What it doesn't do is insist that you follow it against your will.
33 That's Python!"
34
35 -- Tim Peters on comp.lang.python, 2001-06-16
36
37 If you violate these conventions, the worst you'll get is some dirty
38 looks. But some software (such as the Docutils_ docstring processing
39 system [1]_ [2]_) will be aware of the conventions, so following them
40 will get you the best results.
41
42
43 Specification
44 =============
45
46 What is a Docstring?
47 --------------------
48
49 A docstring is a string literal that occurs as the first statement in
50 a module, function, class, or method definition. Such a docstring
51 becomes the ``__doc__`` special attribute of that object.
52
53 All modules should normally have docstrings, and all functions and
54 classes exported by a module should also have docstrings. Public
55 methods (including the ``__init__`` constructor) should also have
56 docstrings. A package may be documented in the module docstring of
57 the ``__init__.py`` file in the package directory.
58
59 String literals occurring elsewhere in Python code may also act as
60 documentation. They are not recognized by the Python bytecode
61 compiler and are not accessible as runtime object attributes (i.e. not
62 assigned to ``__doc__``), but two types of extra docstrings may be
63 extracted by software tools:
64
65 1. String literals occurring immediately after a simple assignment at
66 the top level of a module, class, or ``__init__`` method are called
67 "attribute docstrings".
68
69 2. String literals occurring immediately after another docstring are
70 called "additional docstrings".
71
72 Please see PEP 258, "Docutils Design Specification" [2]_, for a
73 detailed description of attribute and additional docstrings.
74
75 XXX Mention docstrings of 2.2 properties.
76
77 For consistency, always use ``"""triple double quotes"""`` around
78 docstrings. Use ``r"""raw triple double quotes"""`` if you use any
79 backslashes in your docstrings. For Unicode docstrings, use
80 ``u"""Unicode triple-quoted strings"""``.
81
82 There are two forms of docstrings: one-liners and multi-line
83 docstrings.
84
85
86 One-line Docstrings
87 --------------------
88
89 One-liners are for really obvious cases. They should really fit on
90 one line. For example::
91
92 def kos_root():
93 """Return the pathname of the KOS root directory."""
94 global _kos_root
95 if _kos_root: return _kos_root
96 ...
97
98 Notes:
99
100 - Triple quotes are used even though the string fits on one line.
101 This makes it easy to later expand it.
102
103 - The closing quotes are on the same line as the opening quotes. This
104 looks better for one-liners.
105
106 - There's no blank line either before or after the docstring.
107
108 - The docstring is a phrase ending in a period. It prescribes the
109 function or method's effect as a command ("Do this", "Return that"),
110 not as a description; e.g. don't write "Returns the pathname ...".
111
112 - The one-line docstring should NOT be a "signature" reiterating the
113 function/method parameters (which can be obtained by introspection).
114 Don't do::
115
116 def function(a, b):
117 """function(a, b) -> list"""
118
119 This type of docstring is only appropriate for C functions (such as
120 built-ins), where introspection is not possible. However, the
121 nature of the *return value* cannot be determined by introspection,
122 so it should be mentioned. The preferred form for such a docstring
123 would be something like::
124
125 def function(a, b):
126 """Do X and return a list."""
127
128 (Of course "Do X" should be replaced by a useful description!)
129
130
131 Multi-line Docstrings
132 ----------------------
133
134 Multi-line docstrings consist of a summary line just like a one-line
135 docstring, followed by a blank line, followed by a more elaborate
136 description. The summary line may be used by automatic indexing
137 tools; it is important that it fits on one line and is separated from
138 the rest of the docstring by a blank line. The summary line may be on
139 the same line as the opening quotes or on the next line. The entire
140 docstring is indented the same as the quotes at its first line (see
141 example below).
142
143 Insert a blank line before and after all docstrings (one-line or
144 multi-line) that document a class -- generally speaking, the class's
145 methods are separated from each other by a single blank line, and the
146 docstring needs to be offset from the first method by a blank line;
147 for symmetry, put a blank line between the class header and the
148 docstring. Docstrings documenting functions or methods generally
149 don't have this requirement, unless the function or method's body is
150 written as a number of blank-line separated sections -- in this case,
151 treat the docstring as another section, and precede it with a blank
152 line.
153
154 The docstring of a script (a stand-alone program) should be usable as
155 its "usage" message, printed when the script is invoked with incorrect
156 or missing arguments (or perhaps with a "-h" option, for "help").
157 Such a docstring should document the script's function and command
158 line syntax, environment variables, and files. Usage messages can be
159 fairly elaborate (several screens full) and should be sufficient for a
160 new user to use the command properly, as well as a complete quick
161 reference to all options and arguments for the sophisticated user.
162
163 The docstring for a module should generally list the classes,
164 exceptions and functions (and any other objects) that are exported by
165 the module, with a one-line summary of each. (These summaries
166 generally give less detail than the summary line in the object's
167 docstring.) The docstring for a package (i.e., the docstring of the
168 package's ``__init__.py`` module) should also list the modules and
169 subpackages exported by the package.
170
171 The docstring for a function or method should summarize its behavior
172 and document its arguments, return value(s), side effects, exceptions
173 raised, and restrictions on when it can be called (all if applicable).
174 Optional arguments should be indicated. It should be documented
175 whether keyword arguments are part of the interface.
176
177 The docstring for a class should summarize its behavior and list the
178 public methods and instance variables. If the class is intended to be
179 subclassed, and has an additional interface for subclasses, this
180 interface should be listed separately (in the docstring). The class
181 constructor should be documented in the docstring for its ``__init__``
182 method. Individual methods should be documented by their own
183 docstring.
184
185 If a class subclasses another class and its behavior is mostly
186 inherited from that class, its docstring should mention this and
187 summarize the differences. Use the verb "override" to indicate that a
188 subclass method replaces a superclass method and does not call the
189 superclass method; use the verb "extend" to indicate that a subclass
190 method calls the superclass method (in addition to its own behavior).
191
192 *Do not* use the Emacs convention of mentioning the arguments of
193 functions or methods in upper case in running text. Python is case
194 sensitive and the argument names can be used for keyword arguments, so
195 the docstring should document the correct argument names. It is best
196 to list each argument on a separate line. For example::
197
198 def complex(real=0.0, imag=0.0):
199 """Form a complex number.
200
201 Keyword arguments:
202 real -- the real part (default 0.0)
203 imag -- the imaginary part (default 0.0)
204
205 """
206 if imag == 0.0 and real == 0.0: return complex_zero
207 ...
208
209 The BDFL [3]_ recommends inserting a blank line between the last
210 paragraph in a multi-line docstring and its closing quotes, placing
211 the closing quotes on a line by themselves. This way, Emacs'
212 ``fill-paragraph`` command can be used on it.
213
214
215 Handling Docstring Indentation
216 ------------------------------
217
218 Docstring processing tools will strip a uniform amount of indentation
219 from the second and further lines of the docstring, equal to the
220 minimum indentation of all non-blank lines after the first line. Any
221 indentation in the first line of the docstring (i.e., up to the first
222 newline) is insignificant and removed. Relative indentation of later
223 lines in the docstring is retained. Blank lines should be removed
224 from the beginning and end of the docstring.
225
226 Since code is much more precise than words, here is an implementation
227 of the algorithm::
228
229 def trim(docstring):
230 if not docstring:
231 return ''
232 # Convert tabs to spaces (following the normal Python rules)
233 # and split into a list of lines:
234 lines = docstring.expandtabs().splitlines()
235 # Determine minimum indentation (first line doesn't count):
236 indent = sys.maxint
237 for line in lines[1:]:
238 stripped = line.lstrip()
239 if stripped:
240 indent = min(indent, len(line) - len(stripped))
241 # Remove indentation (first line is special):
242 trimmed = [lines[0].strip()]
243 if indent < sys.maxint:
244 for line in lines[1:]:
245 trimmed.append(line[indent:].rstrip())
246 # Strip off trailing and leading blank lines:
247 while trimmed and not trimmed[-1]:
248 trimmed.pop()
249 while trimmed and not trimmed[0]:
250 trimmed.pop(0)
251 # Return a single string:
252 return '\n'.join(trimmed)
253
254 The docstring in this example contains two newline characters and is
255 therefore 3 lines long. The first and last lines are blank::
256
257 def foo():
258 """
259 This is the second line of the docstring.
260 """
261
262 To illustrate::
263
264 >>> print repr(foo.__doc__)
265 '\n This is the second line of the docstring.\n '
266 >>> foo.__doc__.splitlines()
267 ['', ' This is the second line of the docstring.', ' ']
268 >>> trim(foo.__doc__)
269 'This is the second line of the docstring.'
270
271 Once trimmed, these docstrings are equivalent::
272
273 def foo():
274 """A multi-line
275 docstring.
276 """
277
278 def bar():
279 """
280 A multi-line
281 docstring.
282 """
283
284
285 References and Footnotes
286 ========================
287
288 .. [1] PEP 256, Docstring Processing System Framework, Goodger
289 (http://www.python.org/peps/pep-0256.html)
290
291 .. [2] PEP 258, Docutils Design Specification, Goodger
292 (http://www.python.org/peps/pep-0258.html)
293
294 .. [3] Guido van Rossum, Python's creator and Benevolent Dictator For
295 Life.
296
297 .. _Docutils: https://docutils.sourceforge.io/
298
299 .. _Python Style Guide:
300 http://www.python.org/doc/essays/styleguide.html
301
302 .. _Doc-SIG: http://www.python.org/sigs/doc-sig/
303
304
305 Copyright
306 =========
307
308 This document has been placed in the public domain.
309
310
311 Acknowledgements
312 ================
313
314 The "Specification" text comes mostly verbatim from the `Python Style
315 Guide`_ essay by Guido van Rossum.
316
317 This document borrows ideas from the archives of the Python Doc-SIG_.
318 Thanks to all members past and present.
319
320
321 .. Emacs settings
322
323 Local Variables:
324 mode: indented-text
325 mode: rst
326 indent-tabs-mode: nil
327 fill-column: 70
328 sentence-end-double-space: t
329 End: