flavors_numpy

Example NumPy-style docstrings.

This module demonstrates documentation as specified by the NumPy Documentation HOWTO. Docstrings may extend over multiple lines. Sections are created with a section header followed by an underline of equal length.

Example

Examples can be given using either the Example or Examples sections. Sections support any reStructuredText formatting, including literal blocks::

$ python example_numpy.py

Section breaks are created with two blank lines. Section breaks are also implicitly created anytime a new section starts. Section bodies may be indented:

Notes

This is an example of an indented section. It's like any other section, but the body is indented to help it stand out from surrounding text. If a section is indented, then a section break is created by resuming unindented text.

Attributes
  • module_level_variable1 (int): Module level variables may be documented in either the Attributes section of the module docstring, or in an inline docstring immediately following the variable.

    Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it.

  1# Examples taken from:
  2#
  3# - The Napoleon documentation at https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_numpy.html
  4#   License: BSD-3
  5# - https://github.com/numpy/numpydoc/blob/main/doc/example.py
  6#   License: BSD-2
  7#
  8# flake8: noqa
  9# fmt: off
 10"""Example NumPy-style docstrings.
 11
 12This module demonstrates documentation as specified by the `NumPy
 13Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections
 14are created with a section header followed by an underline of equal length.
 15
 16Example
 17-------
 18Examples can be given using either the ``Example`` or ``Examples``
 19sections. Sections support any reStructuredText formatting, including
 20literal blocks::
 21
 22    $ python example_numpy.py
 23
 24
 25Section breaks are created with two blank lines. Section breaks are also
 26implicitly created anytime a new section starts. Section bodies *may* be
 27indented:
 28
 29Notes
 30-----
 31    This is an example of an indented section. It's like any other section,
 32    but the body is indented to help it stand out from surrounding text.
 33
 34If a section is indented, then a section break is created by
 35resuming unindented text.
 36
 37Attributes
 38----------
 39module_level_variable1 : int
 40    Module level variables may be documented in either the ``Attributes``
 41    section of the module docstring, or in an inline docstring immediately
 42    following the variable.
 43
 44    Either form is acceptable, but the two should not be mixed. Choose
 45    one convention to document module level variables and be consistent
 46    with it.
 47
 48
 49.. _NumPy Documentation HOWTO:
 50   https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
 51
 52"""
 53__docformat__ = "numpy"
 54
 55
 56module_level_variable1 = 12345
 57
 58module_level_variable2 = 98765
 59"""int: Module level variable documented inline.
 60
 61The docstring may span multiple lines. The type may optionally be specified
 62on the first line, separated by a colon.
 63"""
 64
 65
 66def function_with_types_in_docstring(param1, param2):
 67    """Example function with types documented in the docstring.
 68
 69    `PEP 484`_ type annotations are supported. If attribute, parameter, and
 70    return types are annotated according to `PEP 484`_, they do not need to be
 71    included in the docstring:
 72
 73    Parameters
 74    ----------
 75    param1 : int
 76        The first parameter.
 77    param2 : str
 78        The second parameter.
 79
 80    Returns
 81    -------
 82    bool
 83        True if successful, False otherwise.
 84
 85    .. _PEP 484:
 86        https://www.python.org/dev/peps/pep-0484/
 87
 88    """
 89
 90
 91def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
 92    """Example function with PEP 484 type annotations.
 93
 94    The return type must be duplicated in the docstring to comply
 95    with the NumPy docstring style.
 96
 97    Parameters
 98    ----------
 99    param1
100        The first parameter.
101    param2
102        The second parameter.
103
104    Returns
105    -------
106    bool
107        True if successful, False otherwise.
108
109    """
110    raise NotImplementedError
111
112
113def module_level_function(param1, param2=None, *args, **kwargs):
114    """This is an example of a module level function.
115
116    Function parameters should be documented in the ``Parameters`` section.
117    The name of each parameter is required. The type and description of each
118    parameter is optional, but should be included if not obvious.
119
120    If *args or **kwargs are accepted,
121    they should be listed as ``*args`` and ``**kwargs``.
122
123    The format for a parameter is::
124
125        name : type
126            description
127
128            The description may span multiple lines. Following lines
129            should be indented to match the first line of the description.
130            The ": type" is optional.
131
132            Multiple paragraphs are supported in parameter
133            descriptions.
134
135    Parameters
136    ----------
137    param1 : int
138        The first parameter.
139    param2 : :obj:`str`, optional
140        The second parameter.
141    *args
142        Variable length argument list.
143    **kwargs
144        Arbitrary keyword arguments.
145
146    Returns
147    -------
148    bool
149        True if successful, False otherwise.
150
151        The return type is not optional. The ``Returns`` section may span
152        multiple lines and paragraphs. Following lines should be indented to
153        match the first line of the description.
154
155        The ``Returns`` section supports any reStructuredText formatting,
156        including literal blocks::
157
158            {
159                'param1': param1,
160                'param2': param2
161            }
162
163    Raises
164    ------
165    AttributeError
166        The ``Raises`` section is a list of all exceptions
167        that are relevant to the interface.
168    ValueError
169        If `param2` is equal to `param1`.
170
171    """
172    if param1 == param2:
173        raise ValueError('param1 may not be equal to param2')
174    return True
175
176
177def example_generator(n):
178    """Generators have a ``Yields`` section instead of a ``Returns`` section.
179
180    Parameters
181    ----------
182    n : int
183        The upper limit of the range to generate, from 0 to `n` - 1.
184
185    Yields
186    ------
187    int
188        The next number in the range of 0 to `n` - 1.
189
190    Examples
191    --------
192    Examples should be written in doctest format, and should illustrate how
193    to use the function.
194
195    >>> print([i for i in example_generator(4)])
196    [0, 1, 2, 3]
197
198    """
199    for i in range(n):
200        yield i
201
202
203class ExampleError(Exception):
204    """Exceptions are documented in the same way as classes.
205
206    The __init__ method may be documented in either the class level
207    docstring, or as a docstring on the __init__ method itself.
208
209    Either form is acceptable, but the two should not be mixed. Choose one
210    convention to document the __init__ method and be consistent with it.
211
212    Note
213    ----
214    Do not include the `self` parameter in the ``Parameters`` section.
215
216    Parameters
217    ----------
218    msg : str
219        Human readable string describing the exception.
220    code : :obj:`int`, optional
221        Numeric error code.
222
223    Attributes
224    ----------
225    msg : str
226        Human readable string describing the exception.
227    code : int
228        Numeric error code.
229
230    """
231
232    def __init__(self, msg, code):
233        self.msg = msg
234        self.code = code
235
236    def add_note(self, note: str):
237        """This method is present on Python 3.11+ and manually added here so that snapshots are consistent."""
238
239
240class ExampleClass(object):
241    """The summary line for a class docstring should fit on one line.
242
243    If the class has public attributes, they may be documented here
244    in an ``Attributes`` section and follow the same formatting as a
245    function's ``Args`` section. Alternatively, attributes may be documented
246    inline with the attribute's declaration (see __init__ method below).
247
248    Properties created with the ``@property`` decorator should be documented
249    in the property's getter method.
250
251    Attributes
252    ----------
253    attr1 : str
254        Description of `attr1`.
255    attr2 : :obj:`int`, optional
256        Description of `attr2`.
257
258    """
259
260    def __init__(self, param1, param2, param3):
261        """Example of docstring on the __init__ method.
262
263        The __init__ method may be documented in either the class level
264        docstring, or as a docstring on the __init__ method itself.
265
266        Either form is acceptable, but the two should not be mixed. Choose one
267        convention to document the __init__ method and be consistent with it.
268
269        Note
270        ----
271        Do not include the `self` parameter in the ``Parameters`` section.
272
273        Parameters
274        ----------
275        param1 : str
276            Description of `param1`.
277        param2 : :obj:`list` of :obj:`str`
278            Description of `param2`. Multiple
279            lines are supported.
280        param3 : :obj:`int`, optional
281            Description of `param3`.
282
283        """
284        self.attr1 = param1
285        self.attr2 = param2
286        self.attr3 = param3  #: Doc comment *inline* with attribute
287
288        #: list of str: Doc comment *before* attribute, with type specified
289        self.attr4 = ["attr4"]
290
291        self.attr5 = None
292        """str: Docstring *after* attribute, with type specified."""
293
294    @property
295    def readonly_property(self):
296        """str: Properties should be documented in their getter method."""
297        return "readonly_property"
298
299    @property
300    def readwrite_property(self):
301        """:obj:`list` of :obj:`str`: Properties with both a getter and setter
302        should only be documented in their getter method.
303
304        If the setter method contains notable behavior, it should be
305        mentioned here.
306        """
307        return ["readwrite_property"]
308
309    @readwrite_property.setter
310    def readwrite_property(self, value):
311        value
312
313    def example_method(self, param1, param2):
314        """Class methods are similar to regular functions.
315
316        Note
317        ----
318        Do not include the `self` parameter in the ``Parameters`` section.
319
320        Parameters
321        ----------
322        param1
323            The first parameter.
324        param2
325            The second parameter.
326
327        Returns
328        -------
329        bool
330            True if successful, False otherwise.
331
332        """
333        return True
334
335    def __special__(self):
336        """By default special members with docstrings are not included.
337
338        Special members are any methods or attributes that start with and
339        end with a double underscore. Any special member with a docstring
340        will be included in the output, if
341        ``napoleon_include_special_with_doc`` is set to True.
342
343        This behavior can be enabled by changing the following setting in
344        Sphinx's conf.py::
345
346            napoleon_include_special_with_doc = True
347
348        """
349        pass
350
351    def __special_without_docstring__(self):
352        pass
353
354    def _private(self):
355        """By default private members are not included.
356
357        Private members are any methods or attributes that start with an
358        underscore and are *not* special. By default they are not included
359        in the output.
360
361        This behavior can be changed such that private members *are* included
362        by changing the following setting in Sphinx's conf.py::
363
364            napoleon_include_private_with_doc = True
365
366        """
367        pass
368
369    def _private_without_docstring(self):
370        pass
371
372
373def foo(var1, var2, *args, long_var_name='hi', **kwargs):
374    r"""Summarize the function in one line.
375
376    Several sentences providing an extended description. Refer to
377    variables using back-ticks, e.g. `var`.
378
379    Parameters
380    ----------
381    var1 : array_like
382        Array_like means all those objects -- lists, nested lists, etc. --
383        that can be converted to an array.  We can also refer to
384        variables like `var1`.
385    var2 : int
386        The type above can either refer to an actual Python type
387        (e.g. ``int``), or describe the type of the variable in more
388        detail, e.g. ``(N,) ndarray`` or ``array_like``.
389    *args : iterable
390        Other arguments.
391    long_var_name : {'hi', 'ho'}, optional
392        Choices in brackets, default first when optional.
393    **kwargs : dict
394        Keyword arguments.
395
396    Returns
397    -------
398    type
399        Explanation of anonymous return value of type ``type``.
400    describe : type
401        Explanation of return value named `describe`.
402    out : type
403        Explanation of `out`.
404    type_without_description
405
406    Other Parameters
407    ----------------
408    only_seldom_used_keywords : type
409        Explanation.
410    common_parameters_listed_above : type
411        Explanation.
412
413    Raises
414    ------
415    BadException
416        Because you shouldn't have done that.
417
418    See Also
419    --------
420    numpy.array : Relationship (optional).
421    numpy.ndarray : Relationship (optional), which could be fairly long, in
422                    which case the line wraps here.
423    numpy.dot, numpy.linalg.norm, numpy.eye
424
425    Notes
426    -----
427    Notes about the implementation algorithm (if needed).
428
429    This can have multiple paragraphs.
430
431    You may include some math:
432
433    .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n}
434
435    And even use a Greek symbol like :math:`\omega` inline.
436
437    References
438    ----------
439    Cite the relevant literature, e.g. [1]_.  You may also cite these
440    references in the notes section above.
441
442    .. [1] O. McNoleg, "The integration of GIS, remote sensing,
443       expert systems and adaptive co-kriging for environmental habitat
444       modelling of the Highland Haggis using object-oriented, fuzzy-logic
445       and neural-network techniques," Computers & Geosciences, vol. 22,
446       pp. 585-588, 1996.
447
448    Examples
449    --------
450    These are written in doctest format, and should illustrate how to
451    use the function.
452
453    >>> a = [1, 2, 3]
454    >>> print([x + 3 for x in a])
455    [4, 5, 6]
456    >>> print("a\nb")
457    a
458    b
459    """
460    # After closing class docstring, there should be one blank line to
461    # separate following codes (according to PEP257).
462    # But for function, method and module, there should be no blank lines
463    # after closing the docstring.
464    pass
465
466
467def invalid_format(test):
468    """
469    In this example, there is no description for the test argument
470
471    Parameters
472    ----------
473    param1
474
475    """
module_level_variable1 = 12345
module_level_variable2 = 98765

int: Module level variable documented inline.

The docstring may span multiple lines. The type may optionally be specified on the first line, separated by a colon.

def function_with_types_in_docstring(param1, param2):
67def function_with_types_in_docstring(param1, param2):
68    """Example function with types documented in the docstring.
69
70    `PEP 484`_ type annotations are supported. If attribute, parameter, and
71    return types are annotated according to `PEP 484`_, they do not need to be
72    included in the docstring:
73
74    Parameters
75    ----------
76    param1 : int
77        The first parameter.
78    param2 : str
79        The second parameter.
80
81    Returns
82    -------
83    bool
84        True if successful, False otherwise.
85
86    .. _PEP 484:
87        https://www.python.org/dev/peps/pep-0484/
88
89    """

Example function with types documented in the docstring.

PEP 484 type annotations are supported. If attribute, parameter, and return types are annotated according to PEP 484, they do not need to be included in the docstring:

Parameters
  • param1 (int): The first parameter.
  • param2 (str): The second parameter.
Returns
  • bool: True if successful, False otherwise.
def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
 92def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
 93    """Example function with PEP 484 type annotations.
 94
 95    The return type must be duplicated in the docstring to comply
 96    with the NumPy docstring style.
 97
 98    Parameters
 99    ----------
100    param1
101        The first parameter.
102    param2
103        The second parameter.
104
105    Returns
106    -------
107    bool
108        True if successful, False otherwise.
109
110    """
111    raise NotImplementedError

Example function with PEP 484 type annotations.

The return type must be duplicated in the docstring to comply with the NumPy docstring style.

Parameters
  • param1: The first parameter.
  • param2: The second parameter.
Returns
  • bool: True if successful, False otherwise.
def module_level_function(param1, param2=None, *args, **kwargs):
114def module_level_function(param1, param2=None, *args, **kwargs):
115    """This is an example of a module level function.
116
117    Function parameters should be documented in the ``Parameters`` section.
118    The name of each parameter is required. The type and description of each
119    parameter is optional, but should be included if not obvious.
120
121    If *args or **kwargs are accepted,
122    they should be listed as ``*args`` and ``**kwargs``.
123
124    The format for a parameter is::
125
126        name : type
127            description
128
129            The description may span multiple lines. Following lines
130            should be indented to match the first line of the description.
131            The ": type" is optional.
132
133            Multiple paragraphs are supported in parameter
134            descriptions.
135
136    Parameters
137    ----------
138    param1 : int
139        The first parameter.
140    param2 : :obj:`str`, optional
141        The second parameter.
142    *args
143        Variable length argument list.
144    **kwargs
145        Arbitrary keyword arguments.
146
147    Returns
148    -------
149    bool
150        True if successful, False otherwise.
151
152        The return type is not optional. The ``Returns`` section may span
153        multiple lines and paragraphs. Following lines should be indented to
154        match the first line of the description.
155
156        The ``Returns`` section supports any reStructuredText formatting,
157        including literal blocks::
158
159            {
160                'param1': param1,
161                'param2': param2
162            }
163
164    Raises
165    ------
166    AttributeError
167        The ``Raises`` section is a list of all exceptions
168        that are relevant to the interface.
169    ValueError
170        If `param2` is equal to `param1`.
171
172    """
173    if param1 == param2:
174        raise ValueError('param1 may not be equal to param2')
175    return True

This is an example of a module level function.

Function parameters should be documented in the Parameters section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious.

If args or *kwargs are accepted, they should be listed as *args and **kwargs.

The format for a parameter is::

name : type
    description

    The description may span multiple lines. Following lines
    should be indented to match the first line of the description.
    The ": type" is optional.

    Multiple paragraphs are supported in parameter
    descriptions.
Parameters
  • param1 (int): The first parameter.
  • param2 (str, optional): The second parameter.
  • *args: Variable length argument list.
  • **kwargs: Arbitrary keyword arguments.
Returns
  • bool: True if successful, False otherwise.

The return type is not optional. The Returns section may span multiple lines and paragraphs. Following lines should be indented to match the first line of the description.

The Returns section supports any reStructuredText formatting, including literal blocks::

{
    'param1': param1,
    'param2': param2
}
Raises
  • AttributeError: The Raises section is a list of all exceptions that are relevant to the interface.
  • ValueError: If param2 is equal to param1.
def example_generator(n):
178def example_generator(n):
179    """Generators have a ``Yields`` section instead of a ``Returns`` section.
180
181    Parameters
182    ----------
183    n : int
184        The upper limit of the range to generate, from 0 to `n` - 1.
185
186    Yields
187    ------
188    int
189        The next number in the range of 0 to `n` - 1.
190
191    Examples
192    --------
193    Examples should be written in doctest format, and should illustrate how
194    to use the function.
195
196    >>> print([i for i in example_generator(4)])
197    [0, 1, 2, 3]
198
199    """
200    for i in range(n):
201        yield i

Generators have a Yields section instead of a Returns section.

Parameters
  • n (int): The upper limit of the range to generate, from 0 to n - 1.
Yields
  • int: The next number in the range of 0 to n - 1.
Examples

Examples should be written in doctest format, and should illustrate how to use the function.

>>> print([i for i in example_generator(4)])
[0, 1, 2, 3]
class ExampleError(builtins.Exception):
204class ExampleError(Exception):
205    """Exceptions are documented in the same way as classes.
206
207    The __init__ method may be documented in either the class level
208    docstring, or as a docstring on the __init__ method itself.
209
210    Either form is acceptable, but the two should not be mixed. Choose one
211    convention to document the __init__ method and be consistent with it.
212
213    Note
214    ----
215    Do not include the `self` parameter in the ``Parameters`` section.
216
217    Parameters
218    ----------
219    msg : str
220        Human readable string describing the exception.
221    code : :obj:`int`, optional
222        Numeric error code.
223
224    Attributes
225    ----------
226    msg : str
227        Human readable string describing the exception.
228    code : int
229        Numeric error code.
230
231    """
232
233    def __init__(self, msg, code):
234        self.msg = msg
235        self.code = code
236
237    def add_note(self, note: str):
238        """This method is present on Python 3.11+ and manually added here so that snapshots are consistent."""

Exceptions are documented in the same way as classes.

The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself.

Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.

Note

Do not include the self parameter in the Parameters section.

Parameters
  • msg (str): Human readable string describing the exception.
  • code (int, optional): Numeric error code.
Attributes
  • msg (str): Human readable string describing the exception.
  • code (int): Numeric error code.
ExampleError(msg, code)
233    def __init__(self, msg, code):
234        self.msg = msg
235        self.code = code
msg
code
def add_note(self, note: str):
237    def add_note(self, note: str):
238        """This method is present on Python 3.11+ and manually added here so that snapshots are consistent."""

This method is present on Python 3.11+ and manually added here so that snapshots are consistent.

Inherited Members
builtins.BaseException
with_traceback
args
class ExampleClass:
241class ExampleClass(object):
242    """The summary line for a class docstring should fit on one line.
243
244    If the class has public attributes, they may be documented here
245    in an ``Attributes`` section and follow the same formatting as a
246    function's ``Args`` section. Alternatively, attributes may be documented
247    inline with the attribute's declaration (see __init__ method below).
248
249    Properties created with the ``@property`` decorator should be documented
250    in the property's getter method.
251
252    Attributes
253    ----------
254    attr1 : str
255        Description of `attr1`.
256    attr2 : :obj:`int`, optional
257        Description of `attr2`.
258
259    """
260
261    def __init__(self, param1, param2, param3):
262        """Example of docstring on the __init__ method.
263
264        The __init__ method may be documented in either the class level
265        docstring, or as a docstring on the __init__ method itself.
266
267        Either form is acceptable, but the two should not be mixed. Choose one
268        convention to document the __init__ method and be consistent with it.
269
270        Note
271        ----
272        Do not include the `self` parameter in the ``Parameters`` section.
273
274        Parameters
275        ----------
276        param1 : str
277            Description of `param1`.
278        param2 : :obj:`list` of :obj:`str`
279            Description of `param2`. Multiple
280            lines are supported.
281        param3 : :obj:`int`, optional
282            Description of `param3`.
283
284        """
285        self.attr1 = param1
286        self.attr2 = param2
287        self.attr3 = param3  #: Doc comment *inline* with attribute
288
289        #: list of str: Doc comment *before* attribute, with type specified
290        self.attr4 = ["attr4"]
291
292        self.attr5 = None
293        """str: Docstring *after* attribute, with type specified."""
294
295    @property
296    def readonly_property(self):
297        """str: Properties should be documented in their getter method."""
298        return "readonly_property"
299
300    @property
301    def readwrite_property(self):
302        """:obj:`list` of :obj:`str`: Properties with both a getter and setter
303        should only be documented in their getter method.
304
305        If the setter method contains notable behavior, it should be
306        mentioned here.
307        """
308        return ["readwrite_property"]
309
310    @readwrite_property.setter
311    def readwrite_property(self, value):
312        value
313
314    def example_method(self, param1, param2):
315        """Class methods are similar to regular functions.
316
317        Note
318        ----
319        Do not include the `self` parameter in the ``Parameters`` section.
320
321        Parameters
322        ----------
323        param1
324            The first parameter.
325        param2
326            The second parameter.
327
328        Returns
329        -------
330        bool
331            True if successful, False otherwise.
332
333        """
334        return True
335
336    def __special__(self):
337        """By default special members with docstrings are not included.
338
339        Special members are any methods or attributes that start with and
340        end with a double underscore. Any special member with a docstring
341        will be included in the output, if
342        ``napoleon_include_special_with_doc`` is set to True.
343
344        This behavior can be enabled by changing the following setting in
345        Sphinx's conf.py::
346
347            napoleon_include_special_with_doc = True
348
349        """
350        pass
351
352    def __special_without_docstring__(self):
353        pass
354
355    def _private(self):
356        """By default private members are not included.
357
358        Private members are any methods or attributes that start with an
359        underscore and are *not* special. By default they are not included
360        in the output.
361
362        This behavior can be changed such that private members *are* included
363        by changing the following setting in Sphinx's conf.py::
364
365            napoleon_include_private_with_doc = True
366
367        """
368        pass
369
370    def _private_without_docstring(self):
371        pass

The summary line for a class docstring should fit on one line.

If the class has public attributes, they may be documented here in an Attributes section and follow the same formatting as a function's Args section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below).

Properties created with the @property decorator should be documented in the property's getter method.

Attributes
  • attr1 (str): Description of attr1.
  • attr2 (int, optional): Description of attr2.
ExampleClass(param1, param2, param3)
261    def __init__(self, param1, param2, param3):
262        """Example of docstring on the __init__ method.
263
264        The __init__ method may be documented in either the class level
265        docstring, or as a docstring on the __init__ method itself.
266
267        Either form is acceptable, but the two should not be mixed. Choose one
268        convention to document the __init__ method and be consistent with it.
269
270        Note
271        ----
272        Do not include the `self` parameter in the ``Parameters`` section.
273
274        Parameters
275        ----------
276        param1 : str
277            Description of `param1`.
278        param2 : :obj:`list` of :obj:`str`
279            Description of `param2`. Multiple
280            lines are supported.
281        param3 : :obj:`int`, optional
282            Description of `param3`.
283
284        """
285        self.attr1 = param1
286        self.attr2 = param2
287        self.attr3 = param3  #: Doc comment *inline* with attribute
288
289        #: list of str: Doc comment *before* attribute, with type specified
290        self.attr4 = ["attr4"]
291
292        self.attr5 = None
293        """str: Docstring *after* attribute, with type specified."""

Example of docstring on the __init__ method.

The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself.

Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.

Note

Do not include the self parameter in the Parameters section.

Parameters
  • param1 (str): Description of param1.
  • param2 (list of str): Description of param2. Multiple lines are supported.
  • param3 (int, optional): Description of param3.
attr1
attr2
attr3
attr4
attr5

str: Docstring after attribute, with type specified.

readonly_property
295    @property
296    def readonly_property(self):
297        """str: Properties should be documented in their getter method."""
298        return "readonly_property"

str: Properties should be documented in their getter method.

readwrite_property
300    @property
301    def readwrite_property(self):
302        """:obj:`list` of :obj:`str`: Properties with both a getter and setter
303        should only be documented in their getter method.
304
305        If the setter method contains notable behavior, it should be
306        mentioned here.
307        """
308        return ["readwrite_property"]

list of str: Properties with both a getter and setter should only be documented in their getter method.

If the setter method contains notable behavior, it should be mentioned here.

def example_method(self, param1, param2):
314    def example_method(self, param1, param2):
315        """Class methods are similar to regular functions.
316
317        Note
318        ----
319        Do not include the `self` parameter in the ``Parameters`` section.
320
321        Parameters
322        ----------
323        param1
324            The first parameter.
325        param2
326            The second parameter.
327
328        Returns
329        -------
330        bool
331            True if successful, False otherwise.
332
333        """
334        return True

Class methods are similar to regular functions.

Note

Do not include the self parameter in the Parameters section.

Parameters
  • param1: The first parameter.
  • param2: The second parameter.
Returns
  • bool: True if successful, False otherwise.
def foo(var1, var2, *args, long_var_name='hi', **kwargs):
374def foo(var1, var2, *args, long_var_name='hi', **kwargs):
375    r"""Summarize the function in one line.
376
377    Several sentences providing an extended description. Refer to
378    variables using back-ticks, e.g. `var`.
379
380    Parameters
381    ----------
382    var1 : array_like
383        Array_like means all those objects -- lists, nested lists, etc. --
384        that can be converted to an array.  We can also refer to
385        variables like `var1`.
386    var2 : int
387        The type above can either refer to an actual Python type
388        (e.g. ``int``), or describe the type of the variable in more
389        detail, e.g. ``(N,) ndarray`` or ``array_like``.
390    *args : iterable
391        Other arguments.
392    long_var_name : {'hi', 'ho'}, optional
393        Choices in brackets, default first when optional.
394    **kwargs : dict
395        Keyword arguments.
396
397    Returns
398    -------
399    type
400        Explanation of anonymous return value of type ``type``.
401    describe : type
402        Explanation of return value named `describe`.
403    out : type
404        Explanation of `out`.
405    type_without_description
406
407    Other Parameters
408    ----------------
409    only_seldom_used_keywords : type
410        Explanation.
411    common_parameters_listed_above : type
412        Explanation.
413
414    Raises
415    ------
416    BadException
417        Because you shouldn't have done that.
418
419    See Also
420    --------
421    numpy.array : Relationship (optional).
422    numpy.ndarray : Relationship (optional), which could be fairly long, in
423                    which case the line wraps here.
424    numpy.dot, numpy.linalg.norm, numpy.eye
425
426    Notes
427    -----
428    Notes about the implementation algorithm (if needed).
429
430    This can have multiple paragraphs.
431
432    You may include some math:
433
434    .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n}
435
436    And even use a Greek symbol like :math:`\omega` inline.
437
438    References
439    ----------
440    Cite the relevant literature, e.g. [1]_.  You may also cite these
441    references in the notes section above.
442
443    .. [1] O. McNoleg, "The integration of GIS, remote sensing,
444       expert systems and adaptive co-kriging for environmental habitat
445       modelling of the Highland Haggis using object-oriented, fuzzy-logic
446       and neural-network techniques," Computers & Geosciences, vol. 22,
447       pp. 585-588, 1996.
448
449    Examples
450    --------
451    These are written in doctest format, and should illustrate how to
452    use the function.
453
454    >>> a = [1, 2, 3]
455    >>> print([x + 3 for x in a])
456    [4, 5, 6]
457    >>> print("a\nb")
458    a
459    b
460    """
461    # After closing class docstring, there should be one blank line to
462    # separate following codes (according to PEP257).
463    # But for function, method and module, there should be no blank lines
464    # after closing the docstring.
465    pass

Summarize the function in one line.

Several sentences providing an extended description. Refer to variables using back-ticks, e.g. var.

Parameters
  • var1 (array_like): Array_like means all those objects -- lists, nested lists, etc. -- that can be converted to an array. We can also refer to variables like var1.
  • var2 (int): The type above can either refer to an actual Python type (e.g. int), or describe the type of the variable in more detail, e.g. (N,) ndarray or array_like.
  • *args (iterable): Other arguments.
  • long_var_name ({'hi', 'ho'}, optional): Choices in brackets, default first when optional.
  • **kwargs (dict): Keyword arguments.
Returns
  • type: Explanation of anonymous return value of type type.
  • describe (type): Explanation of return value named describe.
  • out (type): Explanation of out.
  • type_without_description
Other Parameters
  • only_seldom_used_keywords (type): Explanation.
  • common_parameters_listed_above (type): Explanation.
Raises
  • BadException: Because you shouldn't have done that.
See Also

numpy.array: Relationship (optional).
numpy.ndarray: Relationship (optional), which could be fairly long, in which case the line wraps here.
numpy.dot,, numpy.linalg.norm,, numpy.eye

Notes

Notes about the implementation algorithm (if needed).

This can have multiple paragraphs.

You may include some math:

$$X(e^{j\omega } ) = x(n)e^{ - j\omega n}$$

And even use a Greek symbol like \( \omega \) inline.

References

Cite the relevant literature, e.g. 1. You may also cite these references in the notes section above.

Examples

These are written in doctest format, and should illustrate how to use the function.

>>> a = [1, 2, 3]
>>> print([x + 3 for x in a])
[4, 5, 6]
>>> print("a\nb")
a
b

  1. O. McNoleg, "The integration of GIS, remote sensing, expert systems and adaptive co-kriging for environmental habitat modelling of the Highland Haggis using object-oriented, fuzzy-logic and neural-network techniques," Computers & Geosciences, vol. 22, pp. 585-588, 1996. 

def invalid_format(test):
468def invalid_format(test):
469    """
470    In this example, there is no description for the test argument
471
472    Parameters
473    ----------
474    param1
475
476    """

In this example, there is no description for the test argument

Parameters
  • param1