Skip to content

Commit e3a305f

Browse files
committed
python: Google Docstring made recommended, added interrogate
1 parent 66e8678 commit e3a305f

File tree

1 file changed

+345
-14
lines changed

1 file changed

+345
-14
lines changed

docs/python/docstrings.md

Lines changed: 345 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -121,25 +121,16 @@ write your docstring, it is generally recommended to follow a
121121
template for consistency and also for libraries to be able to
122122
parse your docstring easily.
123123
124-
The official documentation standard for Python is:
125-
126-
- [reStructured Text Docstrings](http://docutils.sourceforge.net/rst.html) (**Recommended**)
127-
128-
Note that the above was recommended by [PEP 287](https://www.python.org/dev/peps/pep-0287/)
129-
124+
The official documentation standard for Python is ReStructed Text docstrings ([PEP 287](https://www.python.org/dev/peps/pep-0287/)).
125+
However, Google docstrings have been widely accepted by the community as such we recommend it.
130126
If you're using using Numpy related libraries, it is better
131-
to use
127+
to use Numpy Docstrings
132128
129+
- [reStructured Text Docstrings](http://docutils.sourceforge.net/rst.html)
130+
- [Google docstrings](https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings) (**Recommended**)
133131
- [Numpy Docstrings](https://numpydoc.readthedocs.io/en/latest/format.html) (**Recommended for AI projects**)
134132
135133
136-
Other docstring templates are also available but it is highly
137-
recommended that you follow the ones above:
138-
139-
- [Google docstrings](https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings)
140-
- [Epytext](http://epydoc.sourceforge.net/epytext.html)
141-
142-
143134
### Where to add docstrings
144135
145136
The developers should add docstrings in the following locations
@@ -162,9 +153,348 @@ the developers a lot of debugging time
162153
- Autodeploy the documentation site using a static deployment tool
163154
to check that your docstrings render correctly
164155
156+
### Checking Docstring coverage
157+
158+
If you want to check docstring coverage in your project. Try interrogate (example below)
159+
160+
- [interrogate](https://interrogate.readthedocs.io/en/latest/)
161+
162+
```
163+
164+
================== Coverage for /Users/lynn/dev/interrogate/ ====================
165+
------------------------------------ Summary ------------------------------------
166+
| Name | Total | Miss | Cover | Cover% |
167+
|---------------------------------------|---------|--------|---------|----------|
168+
| src/interrogate/__init__.py | 1 | 0 | 1 | 100% |
169+
| src/interrogate/__main__.py | 1 | 0 | 1 | 100% |
170+
| src/interrogate/badge_gen.py | 5 | 0 | 5 | 100% |
171+
| src/interrogate/cli.py | 2 | 0 | 2 | 100% |
172+
| src/interrogate/config.py | 6 | 0 | 6 | 100% |
173+
| src/interrogate/coverage.py | 25 | 0 | 25 | 100% |
174+
| src/interrogate/utils.py | 10 | 0 | 10 | 100% |
175+
| src/interrogate/visit.py | 15 | 0 | 15 | 100% |
176+
| tests/functional/__init__.py | 1 | 0 | 1 | 100% |
177+
| tests/functional/test_cli.py | 7 | 0 | 7 | 100% |
178+
| tests/functional/test_coverage.py | 6 | 0 | 6 | 100% |
179+
| tests/unit/__init__.py | 1 | 0 | 1 | 100% |
180+
| tests/unit/test_badge_gen.py | 6 | 0 | 6 | 100% |
181+
| tests/unit/test_config.py | 7 | 0 | 7 | 100% |
182+
| tests/unit/test_utils.py | 13 | 0 | 13 | 100% |
183+
|---------------------------------------|---------|--------|---------|----------|
184+
| TOTAL | 106 | 0 | 106 | 100.0% |
185+
---------------- RESULT: PASSED (minimum: 80.0%, actual: 100.0%) ----------------
186+
187+
```
188+
189+
165190
166191
## Examples
167192
193+
### Google Docstrings (recommended)
194+
195+
```python3
196+
197+
"""Example Google style docstrings.
198+
199+
This module demonstrates documentation as specified by the `Google Python
200+
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
201+
with a section header and a colon followed by a block of indented text.
202+
203+
Example:
204+
Examples can be given using either the ``Example`` or ``Examples``
205+
sections. Sections support any reStructuredText formatting, including
206+
literal blocks::
207+
208+
$ python example_google.py
209+
210+
Section breaks are created by resuming unindented text. Section breaks
211+
are also implicitly created anytime a new section starts.
212+
213+
Attributes:
214+
module_level_variable1 (int): Module level variables may be documented in
215+
either the ``Attributes`` section of the module docstring, or in an
216+
inline docstring immediately following the variable.
217+
218+
Either form is acceptable, but the two should not be mixed. Choose
219+
one convention to document module level variables and be consistent
220+
with it.
221+
222+
Todo:
223+
* For module TODOs
224+
* You have to also use ``sphinx.ext.todo`` extension
225+
226+
.. _Google Python Style Guide:
227+
https://google.github.io/styleguide/pyguide.html
228+
229+
"""
230+
231+
module_level_variable1 = 12345
232+
233+
module_level_variable2 = 98765
234+
"""int: Module level variable documented inline.
235+
236+
The docstring may span multiple lines. The type may optionally be specified
237+
on the first line, separated by a colon.
238+
"""
239+
240+
241+
def function_with_types_in_docstring(param1, param2):
242+
"""Example function with types documented in the docstring.
243+
244+
`PEP 484`_ type annotations are supported. If attribute, parameter, and
245+
return types are annotated according to `PEP 484`_, they do not need to be
246+
included in the docstring:
247+
248+
Args:
249+
param1 (int): The first parameter.
250+
param2 (str): The second parameter.
251+
252+
Returns:
253+
bool: The return value. True for success, False otherwise.
254+
255+
.. _PEP 484:
256+
https://www.python.org/dev/peps/pep-0484/
257+
258+
"""
259+
260+
261+
def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
262+
"""Example function with PEP 484 type annotations.
263+
264+
Args:
265+
param1: The first parameter.
266+
param2: The second parameter.
267+
268+
Returns:
269+
The return value. True for success, False otherwise.
270+
271+
"""
272+
273+
274+
def module_level_function(param1, param2=None, *args, **kwargs):
275+
"""This is an example of a module level function.
276+
277+
Function parameters should be documented in the ``Args`` section. The name
278+
of each parameter is required. The type and description of each parameter
279+
is optional, but should be included if not obvious.
280+
281+
If ``*args`` or ``**kwargs`` are accepted,
282+
they should be listed as ``*args`` and ``**kwargs``.
283+
284+
The format for a parameter is::
285+
286+
name (type): description
287+
The description may span multiple lines. Following
288+
lines should be indented. The "(type)" is optional.
289+
290+
Multiple paragraphs are supported in parameter
291+
descriptions.
292+
293+
Args:
294+
param1 (int): The first parameter.
295+
param2 (:obj:`str`, optional): The second parameter. Defaults to None.
296+
Second line of description should be indented.
297+
*args: Variable length argument list.
298+
**kwargs: Arbitrary keyword arguments.
299+
300+
Returns:
301+
bool: True if successful, False otherwise.
302+
303+
The return type is optional and may be specified at the beginning of
304+
the ``Returns`` section followed by a colon.
305+
306+
The ``Returns`` section may span multiple lines and paragraphs.
307+
Following lines should be indented to match the first line.
308+
309+
The ``Returns`` section supports any reStructuredText formatting,
310+
including literal blocks::
311+
312+
{
313+
'param1': param1,
314+
'param2': param2
315+
}
316+
317+
Raises:
318+
AttributeError: The ``Raises`` section is a list of all exceptions
319+
that are relevant to the interface.
320+
ValueError: If `param2` is equal to `param1`.
321+
322+
"""
323+
if param1 == param2:
324+
raise ValueError('param1 may not be equal to param2')
325+
return True
326+
327+
328+
def example_generator(n):
329+
"""Generators have a ``Yields`` section instead of a ``Returns`` section.
330+
331+
Args:
332+
n (int): The upper limit of the range to generate, from 0 to `n` - 1.
333+
334+
Yields:
335+
int: The next number in the range of 0 to `n` - 1.
336+
337+
Examples:
338+
Examples should be written in doctest format, and should illustrate how
339+
to use the function.
340+
341+
>>> print([i for i in example_generator(4)])
342+
[0, 1, 2, 3]
343+
344+
"""
345+
for i in range(n):
346+
yield i
347+
348+
349+
class ExampleError(Exception):
350+
"""Exceptions are documented in the same way as classes.
351+
352+
The __init__ method may be documented in either the class level
353+
docstring, or as a docstring on the __init__ method itself.
354+
355+
Either form is acceptable, but the two should not be mixed. Choose one
356+
convention to document the __init__ method and be consistent with it.
357+
358+
Note:
359+
Do not include the `self` parameter in the ``Args`` section.
360+
361+
Args:
362+
msg (str): Human readable string describing the exception.
363+
code (:obj:`int`, optional): Error code.
364+
365+
Attributes:
366+
msg (str): Human readable string describing the exception.
367+
code (int): Exception error code.
368+
369+
"""
370+
371+
def __init__(self, msg, code):
372+
self.msg = msg
373+
self.code = code
374+
375+
376+
class ExampleClass:
377+
"""The summary line for a class docstring should fit on one line.
378+
379+
If the class has public attributes, they may be documented here
380+
in an ``Attributes`` section and follow the same formatting as a
381+
function's ``Args`` section. Alternatively, attributes may be documented
382+
inline with the attribute's declaration (see __init__ method below).
383+
384+
Properties created with the ``@property`` decorator should be documented
385+
in the property's getter method.
386+
387+
Attributes:
388+
attr1 (str): Description of `attr1`.
389+
attr2 (:obj:`int`, optional): Description of `attr2`.
390+
391+
"""
392+
393+
def __init__(self, param1, param2, param3):
394+
"""Example of docstring on the __init__ method.
395+
396+
The __init__ method may be documented in either the class level
397+
docstring, or as a docstring on the __init__ method itself.
398+
399+
Either form is acceptable, but the two should not be mixed. Choose one
400+
convention to document the __init__ method and be consistent with it.
401+
402+
Note:
403+
Do not include the `self` parameter in the ``Args`` section.
404+
405+
Args:
406+
param1 (str): Description of `param1`.
407+
param2 (:obj:`int`, optional): Description of `param2`. Multiple
408+
lines are supported.
409+
param3 (list(str)): Description of `param3`.
410+
411+
"""
412+
self.attr1 = param1
413+
self.attr2 = param2
414+
self.attr3 = param3 #: Doc comment *inline* with attribute
415+
416+
#: list(str): Doc comment *before* attribute, with type specified
417+
self.attr4 = ['attr4']
418+
419+
self.attr5 = None
420+
"""str: Docstring *after* attribute, with type specified."""
421+
422+
@property
423+
def readonly_property(self):
424+
"""str: Properties should be documented in their getter method."""
425+
return 'readonly_property'
426+
427+
@property
428+
def readwrite_property(self):
429+
"""list(str): Properties with both a getter and setter
430+
should only be documented in their getter method.
431+
432+
If the setter method contains notable behavior, it should be
433+
mentioned here.
434+
"""
435+
return ['readwrite_property']
436+
437+
@readwrite_property.setter
438+
def readwrite_property(self, value):
439+
value
440+
441+
def example_method(self, param1, param2):
442+
"""Class methods are similar to regular functions.
443+
444+
Note:
445+
Do not include the `self` parameter in the ``Args`` section.
446+
447+
Args:
448+
param1: The first parameter.
449+
param2: The second parameter.
450+
451+
Returns:
452+
True if successful, False otherwise.
453+
454+
"""
455+
return True
456+
457+
def __special__(self):
458+
"""By default special members with docstrings are not included.
459+
460+
Special members are any methods or attributes that start with and
461+
end with a double underscore. Any special member with a docstring
462+
will be included in the output, if
463+
``napoleon_include_special_with_doc`` is set to True.
464+
465+
This behavior can be enabled by changing the following setting in
466+
Sphinx's conf.py::
467+
468+
napoleon_include_special_with_doc = True
469+
470+
"""
471+
pass
472+
473+
def __special_without_docstring__(self):
474+
pass
475+
476+
def _private(self):
477+
"""By default private members are not included.
478+
479+
Private members are any methods or attributes that start with an
480+
underscore and are *not* special. By default they are not included
481+
in the output.
482+
483+
This behavior can be changed such that private members *are* included
484+
by changing the following setting in Sphinx's conf.py::
485+
486+
napoleon_include_private_with_doc = True
487+
488+
"""
489+
pass
490+
491+
def _private_without_docstring(self):
492+
pass
493+
494+
```
495+
496+
### ReStructured Text Doc strings
497+
168498
Here are few examples of docstrings to get you started
169499
170500
```python3
@@ -216,6 +546,7 @@ Thanks to the following
216546
- [Documentation - Python Guide](https://docs.python-guide.org/writing/documentation/)
217547
- [Documenting in Python - DevGuide](https://devguide.python.org/documenting/)
218548
- [daouzli - stackoverflow](https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format)
549+
- [interrogate](https://interrogate.readthedocs.io/en/latest/)
219550
220551
221552

0 commit comments

Comments
 (0)