2 Title: Docstring Conventions
5 Authors: David Goodger <goodger@python.org>,
6 Guido van Rossum <guido@python.org>
7 Discussions-To: doc-sig@python.org
10 Content-Type: text/x-rst
12 Post-History: 13-Jun-2001
18 This PEP documents the semantics and conventions associated with
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.
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.
35 -- Tim Peters on comp.lang.python, 2001-06-16
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.
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.
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.
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:
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".
69 2. String literals occurring immediately after another docstring are
70 called "additional docstrings".
72 Please see PEP 258, "Docutils Design Specification" [2]_, for a
73 detailed description of attribute and additional docstrings.
75 XXX Mention docstrings of 2.2 properties.
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"""``.
82 There are two forms of docstrings: one-liners and multi-line
89 One-liners are for really obvious cases. They should really fit on
90 one line. For example::
93 """Return the pathname of the KOS root directory."""
95 if _kos_root: return _kos_root
100 - Triple quotes are used even though the string fits on one line.
101 This makes it easy to later expand it.
103 - The closing quotes are on the same line as the opening quotes. This
104 looks better for one-liners.
106 - There's no blank line either before or after the docstring.
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 ...".
112 - The one-line docstring should NOT be a "signature" reiterating the
113 function/method parameters (which can be obtained by introspection).
117 """function(a, b) -> list"""
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::
126 """Do X and return a list."""
128 (Of course "Do X" should be replaced by a useful description!)
131 Multi-line Docstrings
132 ----------------------
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
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
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.
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.
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.
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
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).
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::
198 def complex(real=0.0, imag=0.0):
199 """Form a complex number.
202 real -- the real part (default 0.0)
203 imag -- the imaginary part (default 0.0)
206 if imag == 0.0 and real == 0.0: return complex_zero
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.
215 Handling Docstring Indentation
216 ------------------------------
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.
226 Since code is much more precise than words, here is an implementation
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):
237 for line in lines[1:]:
238 stripped = line.lstrip()
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]:
249 while trimmed and not trimmed[0]:
251 # Return a single string:
252 return '\n'.join(trimmed)
254 The docstring in this example contains two newline characters and is
255 therefore 3 lines long. The first and last lines are blank::
259 This is the second line of the docstring.
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.'
271 Once trimmed, these docstrings are equivalent::
285 References and Footnotes
286 ========================
288 .. [1] PEP 256, Docstring Processing System Framework, Goodger
289 (http://www.python.org/peps/pep-0256.html)
291 .. [2] PEP 258, Docutils Design Specification, Goodger
292 (http://www.python.org/peps/pep-0258.html)
294 .. [3] Guido van Rossum, Python's creator and Benevolent Dictator For
297 .. _Docutils: http://docutils.sourceforge.net/
299 .. _Python Style Guide:
300 http://www.python.org/doc/essays/styleguide.html
302 .. _Doc-SIG: http://www.python.org/sigs/doc-sig/
308 This document has been placed in the public domain.
314 The "Specification" text comes mostly verbatim from the `Python Style
315 Guide`_ essay by Guido van Rossum.
317 This document borrows ideas from the archives of the Python Doc-SIG_.
318 Thanks to all members past and present.
325 indent-tabs-mode: nil
327 sentence-end-double-space: t