source: trunk/anuga_documentation/coding_standards/docstring_conventions_GA_version.htm @ 8899

Last change on this file since 8899 was 3831, checked in by ole, 19 years ago

Renamed links to style guides (from spaces to underscores)

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