source: documentation/coding_standards/Docstring Conventions, GA version.htm @ 2434

Last change on this file since 2434 was 2372, checked in by ole, 19 years ago

Moved coding styles

File size: 20.6 KB
Line 
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><!--
3This HTML is auto-generated.  DO NOT EDIT THIS FILE!  If you are writing a new
4PEP, see http://www.python.org/peps/pep-0001.html for instructions and links
5to templates.  DO NOT USE THIS HTML FILE AS YOUR TEMPLATE!
6-->
7  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
8  <meta name="generator" content="Docutils 0.2.8: http://docutils.sourceforge.net/"><title>PEP 257 -- Docstring Conventions</title>
9 
10  <link rel="stylesheet" href="Docstring%20Conventions,%20GA%20version_files/pep.css" type="text/css"></head>
11
12
13
14<body bgcolor="white">
15<table class="navigation" border="0" cellpadding="0" cellspacing="0" width="100%">
16<tbody><tr><td class="navicon" height="35" width="150">
17<a href="http://www.python.org/" title="Python Home Page">
18<img src="Docstring%20Conventions,%20GA%20version_files/PyBanner012.gif" alt="[Python]" border="0" height="35" width="150"></a></td>
19<td class="textlinks" align="left">
20[<b><a href="http://www.python.org/">Python Home</a></b>]
21[<b><a href="http://www.python.org/peps/">PEP Index</a></b>]
22[<b><a href="http://www.python.org/peps/pep-0257.txt">PEP Source</a></b>]
23</td></tr></tbody></table>
24<div class="document">
25<table class="rfc2822 field-list" frame="void" rules="none">
26<col class="field-name">
27<col class="field-body">
28<tbody valign="top">
29<tr class="field"><th class="field-name">PEP:</th><td class="field-body">257</td>
30</tr>
31<tr class="field"><th class="field-name">Title:</th><td class="field-body">Docstring Conventions</td>
32</tr>
33<tr class="field"><th class="field-name">Version:</th><td class="field-body">1.8</td>
34</tr>
35<tr class="field"><th class="field-name">Last-Modified:</th><td class="field-body"><a class="reference" href="http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/nondist/peps/pep-0257.txt">2002/11/30 01:49:37</a></td>
36</tr>
37<tr class="field"><th class="field-name">Author:</th><td class="field-body">David Goodger &lt;goodger at users.sourceforge.net&gt;,
38Guido van Rossum &lt;guido at python.org&gt;</td>
39</tr>
40<tr class="field"><th class="field-name">Discussions-To:</th><td class="field-body"><a class="reference" href="mailto:doc-sig@python.org?subject=PEP%20257">doc-sig at python.org</a></td>
41</tr>
42<tr class="field"><th class="field-name">Status:</th><td class="field-body">Active</td>
43</tr>
44<tr class="field"><th class="field-name">Type:</th><td class="field-body">Informational</td>
45</tr>
46<tr class="field"><th class="field-name">Content-Type:</th><td class="field-body"><a class="reference" href="http://www.python.org/peps/pep-0012.html">text/x-rst</a></td>
47</tr>
48<tr class="field"><th class="field-name">Created:</th><td class="field-body">29-May-2001</td>
49</tr>
50<tr class="field"><th class="field-name">Post-History:</th><td class="field-body">13-Jun-2001</td>
51</tr>
52</tbody>
53</table>
54<hr>
55<div class="contents topic" id="contents">
56<p class="topic-title"><a name="contents">Contents</a></p>
57<ul class="simple">
58<li><a class="reference" href="#abstract" id="id14" name="id14">Abstract</a></li>
59<li><a class="reference" href="#rationale" id="id15" name="id15">Rationale</a></li>
60<li><a class="reference" href="#specification" id="id16" name="id16">Specification</a><ul>
61<li><a class="reference" href="#what-is-a-docstring" id="id17" name="id17">What is a Docstring?</a></li>
62<li><a class="reference" href="#one-line-docstrings" id="id18" name="id18">One-line Docstrings</a></li>
63<li><a class="reference" href="#multi-line-docstrings" id="id19" name="id19">Multi-line Docstrings</a></li>
64<li><a class="reference" href="#handling-docstring-indentation" id="id20" name="id20">Handling Docstring Indentation</a></li>
65</ul>
66</li>
67<li><a class="reference" href="#references-and-footnotes" id="id21" name="id21">References and Footnotes</a></li>
68<li><a class="reference" href="#copyright" id="id22" name="id22">Copyright</a></li>
69<li><a class="reference" href="#acknowledgements" id="id23" name="id23">Acknowledgements</a></li>
70</ul>
71</div>
72<div class="section" id="abstract">
73<h1><a class="toc-backref" href="#id14" name="abstract">Abstract</a></h1>
74<p>This PEP documents the semantics and conventions associated with
75Python docstrings.</p>
76</div>
77<div class="section" id="rationale">
78<h1><a class="toc-backref" href="#id15" name="rationale">Rationale</a></h1>
79<p>The aim of this PEP is to standardize the high-level structure of
80docstrings: what they should contain, and how to say it (without
81touching on any markup syntax within docstrings).  The PEP contains
82conventions, not laws or syntax.</p>
83<blockquote>
84<p>"A universal convention supplies all of maintainability, clarity,
85consistency, and a foundation for good programming habits too.
86What it doesn't do is insist that you follow it against your will.
87That's Python!"</p>
88<p>-- Tim Peters on comp.lang.python, 2001-06-16</p>
89</blockquote>
90<p>If you violate these conventions, the worst you'll get is some dirty
91looks.  But some software (such as the <a class="reference" href="http://docutils.sourceforge.net/">Docutils</a> <a class="footnote-reference" href="#id8" id="id9" name="id9">[4]</a> docstring processing
92system <a class="footnote-reference" href="#id5" id="id1" name="id1">[1]</a> <a class="footnote-reference" href="#id6" id="id2" name="id2">[2]</a>) will be aware of the conventions, so following them
93will get you the best results.</p>
94</div>
95<div class="section" id="specification">
96<h1><a class="toc-backref" href="#id16" name="specification">Specification</a></h1>
97<div class="section" id="what-is-a-docstring">
98<h2><a class="toc-backref" href="#id17" name="what-is-a-docstring">What is a Docstring?</a></h2>
99<p>A docstring is a string literal that occurs as the first statement in
100a module, function, class, or method definition.  Such a docstring
101becomes the <tt class="literal"><span class="pre">__doc__</span></tt> special attribute of that object.</p>
102<p>All modules should normally have docstrings, and all functions and
103classes exported by a module should also have docstrings.  Public
104methods (including the <tt class="literal"><span class="pre">__init__</span></tt> constructor) should also have
105docstrings.  A package may be documented in the module docstring of
106the <tt class="literal"><span class="pre">__init__.py</span></tt> file in the package directory.</p>
107<p>String literals occurring elsewhere in Python code may also act as
108documentation.  They are not recognized by the Python bytecode
109compiler and are not accessible as runtime object attributes (i.e. not
110assigned to <tt class="literal"><span class="pre">__doc__</span></tt>), but two types of extra docstrings may be
111extracted by software tools:</p>
112<ol class="arabic simple">
113<li>String literals occurring immediately after a simple assignment at
114the top level of a module, class, or <tt class="literal"><span class="pre">__init__</span></tt> method are called
115"attribute docstrings".</li>
116<li>String literals occurring immediately after another docstring are
117called "additional docstrings".</li>
118</ol>
119<p>Please see <a class="reference" href="http://www.python.org/peps/pep-0258.html">PEP 258</a>, "Docutils Design Specification" <a class="footnote-reference" href="#id6" id="id3" name="id3">[2]</a>, for a
120detailed description of attribute and additional docstrings.</p>
121<p>XXX Mention docstrings of 2.2 properties.</p>
122<p>For consistency, always use <tt class="literal"><span class="pre">"""triple</span> <span class="pre">double</span> <span class="pre">quotes"""</span></tt> around
123docstrings.  Use <tt class="literal"><span class="pre">r"""raw</span> <span class="pre">triple</span> <span class="pre">double</span> <span class="pre">quotes"""</span></tt> if you use any
124backslashes in your docstrings.  For Unicode docstrings, use
125<tt class="literal"><span class="pre">u"""Unicode</span> <span class="pre">triple-quoted</span> <span class="pre">strings"""</span></tt>.</p>
126<p>There are two forms of docstrings: one-liners and multi-line
127docstrings.</p>
128</div>
129<div class="section" id="one-line-docstrings">
130<h2><a class="toc-backref" href="#id18" name="one-line-docstrings">One-line Docstrings</a></h2>
131<p>One-liners are for really obvious cases.  They should really fit on
132one line.  For example:</p>
133<pre class="literal-block">def kos_root():
134    """Return the pathname of the KOS root directory."""
135    global _kos_root
136    if _kos_root: return _kos_root
137    ...
138</pre>
139<p>Notes:</p>
140<ul>
141<li><p class="first">Triple quotes are used even though the string fits on one line.
142This makes it easy to later expand it.</p>
143</li>
144<li><p class="first">The closing quotes are on the same line as the opening quotes.  This
145looks better for one-liners.</p>
146</li>
147<li><p class="first">There's no blank line either before or after the docstring.</p>
148</li>
149<li><p class="first">The docstring is a phrase ending in a period.  It prescribes the
150function or method's effect as a command ("Do this", "Return that"),
151not as a description; e.g. don't write "Returns the pathname ...".</p>
152</li>
153<li><p class="first">The one-line docstring should NOT be a "signature" reiterating the
154function/method parameters (which can be obtained by introspection).
155Don't do:</p>
156<pre class="literal-block">def function(a, b):
157    """function(a, b) -&gt; list"""
158</pre>
159<p>This type of docstring is only appropriate for C functions (such as
160built-ins), where introspection is not possible.  However, the
161nature of the <em>return value</em> cannot be determined by introspection,
162so it should be mentioned.  The preferred form for such a docstring
163would be something like:</p>
164<pre class="literal-block">def function(a, b):
165    """Do X and return a list."""
166</pre>
167<p>(Of course "Do X" should be replaced by a useful description!)</p>
168</li>
169</ul>
170</div>
171<div class="section" id="multi-line-docstrings">
172<h2><a class="toc-backref" href="#id19" name="multi-line-docstrings">Multi-line Docstrings</a></h2>
173<p>Multi-line docstrings consist of a summary line just like a one-line
174docstring, followed by a blank line, followed by a more elaborate
175description.  The summary line may be used by automatic indexing
176tools; it is important that it fits on one line and is separated from
177the rest of the docstring by a blank line.  The summary line may be on
178the same line as the opening quotes or on the next line.  The entire
179docstring is indented the same as the quotes at its first line (see
180example below).</p>
181<p>Insert a blank line before and after all docstrings (one-line or
182multi-line) that document a class -- generally speaking, the class's
183methods are separated from each other by a single blank line, and the
184docstring needs to be offset from the first method by a blank line;
185for symmetry, put a blank line between the class header and the
186docstring.  Docstrings documenting functions or methods generally
187don't have this requirement, unless the function or method's body is
188written as a number of blank-line separated sections -- in this case,
189treat the docstring as another section, and precede it with a blank
190line.</p>
191<p>The docstring of a script (a stand-alone program) should be usable as
192its "usage" message, printed when the script is invoked with incorrect
193or missing arguments (or perhaps with a "-h" option, for "help").
194Such a docstring should document the script's function and command
195line syntax, environment variables, and files.  Usage messages can be
196fairly elaborate (several screens full) and should be sufficient for a
197new user to use the command properly, as well as a complete quick
198reference to all options and arguments for the sophisticated user.</p>
199<p>The docstring for a module should generally list the classes,
200exceptions and functions (and any other objects) that are exported by
201the module, with a one-line summary of each.  (These summaries
202generally give less detail than the summary line in the object's
203docstring.)  The docstring for a package (i.e., the docstring of the
204package's <tt class="literal"><span class="pre">__init__.py</span></tt> module) should also list the modules and
205subpackages exported by the package.</p>
206<p>The docstring for a function or method should summarize its behavior
207and document its arguments, return value(s), side effects, exceptions
208raised, and restrictions on when it can be called (all if applicable).
209Optional arguments should be indicated.  It should be documented
210whether keyword arguments are part of the interface.</p>
211<p>The docstring for a class should summarize its behavior and list the
212public methods and instance variables.  If the class is intended to be
213subclassed, and has an additional interface for subclasses, this
214interface should be listed separately (in the docstring).  The class
215constructor should be documented in the docstring for its <tt class="literal"><span class="pre">__init__</span></tt>
216method.  Individual methods should be documented by their own
217docstring.</p>
218<p>If a class subclasses another class and its behavior is mostly
219inherited from that class, its docstring should mention this and
220summarize the differences.  Use the verb "override" to indicate that a
221subclass method replaces a superclass method and does not call the
222superclass method; use the verb "extend" to indicate that a subclass
223method calls the superclass method (in addition to its own behavior).</p>
224<p><em>Do not</em> use the Emacs convention of mentioning the arguments of
225functions or methods in upper case in running text.  Python is case
226sensitive and the argument names can be used for keyword arguments, so
227the docstring should document the correct argument names.  It is best
228to list each argument on a separate line.  For example:</p>
229<pre class="literal-block">def complex(real=0.0, imag=0.0):
230    """Form a complex number.
231
232    Keyword arguments:
233    real -- the real part (default 0.0)
234    imag -- the imaginary part (default 0.0)
235
236    """
237    if imag == 0.0 and real == 0.0: return complex_zero
238    ...
239</pre>
240<p>The BDFL <a class="footnote-reference" href="#id7" id="id4" name="id4">[3]</a> recommends inserting a blank line between the last
241paragraph in a multi-line docstring and its closing quotes, placing
242the closing quotes on a line by themselves.  This way, Emacs'
243<tt class="literal"><span class="pre">fill-paragraph</span></tt> command can be used on it.</p>
244</div>
245<div class="section" id="handling-docstring-indentation">
246<h2><a class="toc-backref" href="#id20" name="handling-docstring-indentation">Handling Docstring Indentation</a></h2>
247<p>Docstring processing tools will strip a uniform amount of indentation
248from the second and further lines of the docstring, equal to the
249minimum indentation of all non-blank lines after the first line.  Any
250indentation in the first line of the docstring (i.e., up to the first
251newline) is insignificant and removed.  Relative indentation of later
252lines in the docstring is retained.  Blank lines should be removed
253from the beginning and end of the docstring.</p>
254<p>Since code is much more precise than words, here is an implementation
255of the algorithm:</p>
256<pre class="literal-block">def trim(docstring):
257    if not docstring:
258        return ''
259    # Convert tabs to spaces (following the normal Python rules)
260    # and split into a list of lines:
261    lines = docstring.expandtabs().splitlines()
262    # Determine minimum indentation (first line doesn't count):
263    indent = sys.maxint
264    for line in lines[1:]:
265        stripped = line.lstrip()
266        if stripped:
267            indent = min(indent, len(line) - len(stripped))
268    # Remove indentation (first line is special):
269    trimmed = [lines[0].strip()]
270    if indent &lt; sys.maxint:
271        for line in lines[1:]:
272            trimmed.append(line[indent:].rstrip())
273    # Strip off trailing and leading blank lines:
274    while trimmed and not trimmed[-1]:
275        trimmed.pop()
276    while trimmed and not trimmed[0]:
277        trimmed.pop(0)
278    # Return a single string:
279    return '\n'.join(trimmed)
280</pre>
281<p>The docstring in this example contains two newline characters and is
282therefore 3 lines long.  The first and last lines are blank:</p>
283<pre class="literal-block">def foo():
284    """
285    This is the second line of the docstring.
286    """
287</pre>
288<p>To illustrate:</p>
289<pre class="literal-block">&gt;&gt;&gt; print repr(foo.__doc__)
290'\n    This is the second line of the docstring.\n    '
291&gt;&gt;&gt; foo.__doc__.splitlines()
292['', '    This is the second line of the docstring.', '    ']
293&gt;&gt;&gt; trim(foo.__doc__)
294'This is the second line of the docstring.'
295</pre>
296<p>Once trimmed, these docstrings are equivalent:</p>
297<pre class="literal-block">def foo():
298    """A multi-line
299    docstring.
300    """
301
302def bar():
303    """
304    A multi-line
305    docstring.
306    """
307</pre>
308</div>
309</div>
310<div class="section" id="references-and-footnotes">
311<h1><a class="toc-backref" href="#id21" name="references-and-footnotes">References and Footnotes</a></h1>
312<table class="footnote" id="id5" frame="void" rules="none">
313<colgroup><col class="label"><col></colgroup>
314<tbody valign="top">
315<tr><td class="label"><a class="fn-backref" href="#id1" name="id5">[1]</a></td><td><a class="reference" href="http://www.python.org/peps/pep-0256.html">PEP 256</a>, Docstring Processing System Framework, Goodger
316(<a class="reference" href="http://www.python.org/peps/pep-0256.html">http://www.python.org/peps/pep-0256.html</a>)</td></tr>
317</tbody>
318</table>
319<table class="footnote" id="id6" frame="void" rules="none">
320<colgroup><col class="label"><col></colgroup>
321<tbody valign="top">
322<tr><td class="label"><a name="id6">[2]</a></td><td><em>(<a class="fn-backref" href="#id2">1</a>, <a class="fn-backref" href="#id3">2</a>)</em> <a class="reference" href="http://www.python.org/peps/pep-0258.html">PEP 258</a>, Docutils Design Specification, Goodger
323(<a class="reference" href="http://www.python.org/peps/pep-0258.html">http://www.python.org/peps/pep-0258.html</a>)</td></tr>
324</tbody>
325</table>
326<table class="footnote" id="id7" frame="void" rules="none">
327<colgroup><col class="label"><col></colgroup>
328<tbody valign="top">
329<tr><td class="label"><a class="fn-backref" href="#id4" name="id7">[3]</a></td><td>Guido van Rossum, Python's creator and Benevolent Dictator For
330Life.</td></tr>
331</tbody>
332</table>
333<table class="footnote" id="id8" frame="void" rules="none">
334<colgroup><col class="label"><col></colgroup>
335<tbody valign="top">
336<tr><td class="label"><a class="fn-backref" href="#id9" name="id8">[4]</a></td><td><a class="reference" href="http://docutils.sourceforge.net/">http://docutils.sourceforge.net/</a></td></tr>
337</tbody>
338</table>
339<table class="footnote" id="id10" frame="void" rules="none">
340<colgroup><col class="label"><col></colgroup>
341<tbody valign="top">
342<tr><td class="label"><a class="fn-backref" href="#id11" name="id10">[5]</a></td><td><a class="reference" href="http://www.python.org/doc/essays/styleguide.html">http://www.python.org/doc/essays/styleguide.html</a></td></tr>
343</tbody>
344</table>
345<table class="footnote" id="id12" frame="void" rules="none">
346<colgroup><col class="label"><col></colgroup>
347<tbody valign="top">
348<tr><td class="label"><a class="fn-backref" href="#id13" name="id12">[6]</a></td><td><a class="reference" href="http://www.python.org/sigs/doc-sig/">http://www.python.org/sigs/doc-sig/</a></td></tr>
349</tbody>
350</table>
351</div>
352<div class="section" id="copyright">
353<h1><a class="toc-backref" href="#id22" name="copyright">Copyright</a></h1>
354<p>This document has been placed in the public domain.</p>
355</div>
356<div class="section" id="acknowledgements">
357<h1><a class="toc-backref" href="#id23" name="acknowledgements">Acknowledgements</a></h1>
358<p>The "Specification" text comes mostly verbatim from the <a class="reference" href="http://www.python.org/doc/essays/styleguide.html">Python Style
359Guide</a> <a class="footnote-reference" href="#id10" id="id11" name="id11">[5]</a> essay by Guido van Rossum.</p>
360<p>This document borrows ideas from the archives of the Python <a class="reference" href="http://www.python.org/sigs/doc-sig/">Doc-SIG</a> <a class="footnote-reference" href="#id12" id="id13" name="id13">[6]</a>.
361Thanks to all members past and present.</p>
362<!-- Local Variables:
363mode: indented-text
364indent-tabs-mode: nil
365fill-column: 70
366sentence-end-double-space: t
367End: -->
368</div>
369</div>
370
371<hr class="footer">
372<div class="footer">
373<a class="reference" href="http://www.python.org/peps/pep-0257.txt">View document source</a>.
374Generated on: 2005-10-26 02:30 UTC.
375Generated by <a class="reference" href="http://docutils.sourceforge.net/">Docutils</a> from <a class="reference" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> source.
376</div>
377</body></html>
Note: See TracBrowser for help on using the repository browser.