a598d43060290edeac6a4777a17a885703112eba
[python-guide.git] / docs / writing / documentation.rst
1 Documenting Your Code
2 =====================
3
4 With readability of the code being a main focus for Python developers, proper
5 commenting is naturally important. Some best practice apply to code comments
6 and project documents, depending on the scope of the project.
7
8 Project documents
9 -----------------
10
11 A README file at the root directory give general information to the users and
12 the maintainers. It should be raw text or written in some very easy to read
13 markup, such as reStructuredText and Markdown. It should contain a few lines
14 explaining the purpose of the project or the library (without assuming the user
15 knows anything about the project), the url of the main source for the software,
16 and some basic credit information. This file is the main entry point for
17 readers of the code.
18
19 An INSTALL file is less often necessary with python, except if the dependencies
20 are complex or unusual, or if some C modules need to be compiled before use.
21 The installation instructions are often reduced to one command, such as ``pip
22 install module`` or ``python setup.py install`` and added to the README file.
23
24 A LICENSE file should always be present and specify the license under which the
25 software is made available to the public.
26
27 A TODO file or a TODO section in README should list the planned modifications
28 of the code.
29
30 A CHANGELOG file or section in README should compile a short overview of the
31 changes in the code base for the latest versions.
32
33 Documentation
34 -------------
35
36 As the project or library reaches a certain level of complexity, it may require
37 a fuller documentation, which can be of different flavors:
38
39 The introduction may show a very short overview of what can be done with the
40 product, using one or two extremely simplified use cases.
41
42 The tutorials will show in more details some main use cases. The reader will
43 follow a step-by-step procedure to set-up a working prototype.
44
45 The API reference, which is often generated automatically from the code, will
46 list all publicly available interfaces, their parameters and their return
47 values, with an explanation of their use.
48
49 Some documents intended for developers might give guidance about code
50 convention and general design decision of the project.
51
52 Comments
53 --------
54
55 Comments are written directly inside the code, either using the hash sign (#)
56 or a docstring_.
57
58 .. _docstring: docstrings_
59
60 Finding the correct balance between undocumented code and verbose and useless
61 comment boilerplates is difficult, and is the subject of heated discussion
62 among developers.
63
64 The following guidelines seem to be most commonly agreed upon:
65
66 **Wrong or outdated comments are worse than no comments at all.** Following the
67 saying that it is better, on a boat, to know that we do not know were we are
68 than to wrongly believe we know where we are, wrong or outdated comments can be
69 misleading for the maintainers, slow down considerably bug hunting or
70 refactoring, and then, when discovered wrong, they will throw suspicion on all
71 other comments in the code, regardless of their individual correctness.
72
73 **There's no need to comment perfect code...** An hypothetical perfectly readable
74 code, with a crystal clear logic stream, expressive variable and function
75 names, orthogonal segmentation passing exactly between the flesh and the bones,
76 and no implicit assumptions of any kind, would not require any comment at all.
77 When striving for coding excellence, it is useful to see any existing comment,
78 or any feeling of a need for a comment, as the sign that the code do not
79 express clearly enough its intent and can be improved.
80
81 **.. but no code is perfect.**  Perfect code is a chimera, it exists only in
82 our dreams.  In real life, a code base is full of trade offs, and comments are
83 often needed in the most difficult parts. Moreover, any special case, any
84 obscure hack, any monkey patch and any ugly workaround MUST be signaled and
85 explained by a proper comment. This should be enforced by the law!
86
87 **TODOs** are special comments that a developer write as a reminder for later
88 use. It is said that its original intent was that someone might, one day,
89 search for the string "TODO" in the code base and actually roll their sleeves
90 and start *to do the TODOs*. There is no available record that it ever
91 happened. However, TODOs comment are still very useful, because they mark the
92 current limits of the code, and it is not unlikely that, when required to add a
93 new behavior to the actual code, looking at the TODOs will show where to start.
94
95 **Do not use triple-quote strings to comment code.** A common operation when
96 modifying code is to comment out some lines or even a full function or class
97 definition. This can be done by adding triple-quotes around the code block to
98 be skipped, but this is not a good practice, because line-oriented command-line
99 tools such as ``grep`` will not be aware that the commented code is inactive.
100 It is better to add hashes at the proper indentation level for every commented
101 line. Good editors allow to do this with few keystrokes (ctrl-v on Vim).
102
103 **Bad**
104
105 .. code-block:: python
106
107     def tricky_function():
108         '''
109         Commented out because its breaks something.
110         if foo:
111             do_bar()
112         '''
113         return baz
114
115     def tricky_function():
116         # Commented out because its breaks something.
117         #if foo:
118             #do_bar()
119         return baz
120
121
122     def tricky_function():
123     # Commented out because its breaks something.
124     #   if foo:
125     #       do_bar()
126         return baz
127
128 **Good**
129
130 .. code-block:: python
131
132     def tricky_function():
133         # Commented out because its breaks something.
134         #if foo:
135         #    do_bar()
136         return baz
137
138 Note that comment text is properly written and separated from the hash by a
139 space. Commented code is not separated from the hash by an additional space;
140 this helps when uncommented the code.
141
142 The Basics
143 ::::::::::
144
145
146 Code Comments
147 -------------
148
149 Information regarding code comments is taken from PEP 008 (http://www.python.org/dev/peps/pep-0008/).
150 Block comment styling should be used when commenting out multiple lines of code.: ::
151
152     Block comments generally apply to some (or all) code that follows them,
153     and are indented to the same level as that code.  Each line of a block
154     comment starts with a # and a single space (unless it is indented text
155     inside the comment).
156     Paragraphs inside a block comment are separated by a line containing a
157     single #.
158
159 In-line comments are used for individual lines and should be used sparingly.: ::
160
161     An inline comment is a comment on the same line as a statement.  Inline
162     comments should be separated by at least two spaces from the statement.
163     They should start with a # and a single space.
164     Inline comments are unnecessary and in fact distracting if they state
165     the obvious.  Don't do this:
166         x = x + 1                 # Increment x
167     But sometimes, this is useful: ::
168         x = x + 1                 # Compensate for border
169
170 Docstrings
171 -----------
172
173 PEP 257 is the primary reference for docstrings. (http://www.python.org/dev/peps/pep-0257/)
174
175 There are two types of docstrings, one-line and multi-line.  Their names
176 should be fairly self explanatory.
177 One-line docstrings: ::
178
179     def kos_root():
180         """Return the pathname of the KOS root directory."""
181         global _kos_root
182         if _kos_root: return _kos_root
183         ...
184
185 Multi-line docstrings: ::
186
187     def complex(real=0.0, imag=0.0):
188         """Form a complex number.
189
190         Keyword arguments:
191         real -- the real part (default 0.0)
192         imag -- the imaginary part (default 0.0)
193
194         """
195         if imag == 0.0 and real == 0.0: return complex_zero
196         ...
197
198
199 .. _sphinx-ref:
200
201
202 Sphinx
203 ------
204
205 Sphinx_ is a tool which converts documentation in the :ref:`restructuredtext-ref`
206 markup language into a range of output formats including HTML, LaTeX (for
207 printable PDF versions), manual pages and plain text.
208
209 There is also a great free hosting for your Sphinx_ docs: `Read The Docs`_
210
211 .. note:: This Guide is built with Sphinx_ and hosted on `Read The Docs`_
212
213 .. _Sphinx: http://sphinx.pocoo.org
214 .. _Read The Docs: http://readthedocs.org
215
216 .. _restructuredtext-ref:
217
218
219 reStructuredText
220 ----------------
221
222 Most Python documentation is written with reStructuredText_. The
223 `reStructuredText Primer <http://sphinx.pocoo.org/rest.html>`_ and the
224 `reStructuredText Quick Reference <http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_
225 should help you familiarize yourself with its syntax.
226
227 .. _reStructuredText: http://docutils.sourceforge.net/rst.html
228
229 Other Tools
230 :::::::::::
231
232
233 Epydoc
234 ------
235 `Epydoc <http://epydoc.sourceforge.net/>`_ generates API documentation based on docstrings. 
236 Epydoc is able to parse docstrings marked up with :ref:`reStructuredText-ref`, 
237 `Javadoc <http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html#javadocdocuments>`_, 
238 `epytext <http://epydoc.sourceforge.net/manual-epytext.html>`_ or plaintext. 
239 It supports various output formats, most notable HTML, PDF or LaTeX documents.
240
241 The development of Epydoc is discontinued. You should use :ref:`sphinx-ref` instead.
242
243 pycco / docco / shocco
244 ----------------------
245
246 Ronn
247 ----