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    def with_traceback(self, object, /):
240        """This method has a changed docstring in Python 3.13+ and is manually added here so that snapshots are consistent."""
241
242class ExampleClass(object):
243    """The summary line for a class docstring should fit on one line.
244
245    If the class has public attributes, they may be documented here
246    in an ``Attributes`` section and follow the same formatting as a
247    function's ``Args`` section. Alternatively, attributes may be documented
248    inline with the attribute's declaration (see __init__ method below).
249
250    Properties created with the ``@property`` decorator should be documented
251    in the property's getter method.
252
253    Attributes
254    ----------
255    attr1 : str
256        Description of `attr1`.
257    attr2 : :obj:`int`, optional
258        Description of `attr2`.
259
260    """
261
262    def __init__(self, param1, param2, param3):
263        """Example of docstring on the __init__ method.
264
265        The __init__ method may be documented in either the class level
266        docstring, or as a docstring on the __init__ method itself.
267
268        Either form is acceptable, but the two should not be mixed. Choose one
269        convention to document the __init__ method and be consistent with it.
270
271        Note
272        ----
273        Do not include the `self` parameter in the ``Parameters`` section.
274
275        Parameters
276        ----------
277        param1 : str
278            Description of `param1`.
279        param2 : :obj:`list` of :obj:`str`
280            Description of `param2`. Multiple
281            lines are supported.
282        param3 : :obj:`int`, optional
283            Description of `param3`.
284
285        """
286        self.attr1 = param1
287        self.attr2 = param2
288        self.attr3 = param3  #: Doc comment *inline* with attribute
289
290        #: list of str: Doc comment *before* attribute, with type specified
291        self.attr4 = ["attr4"]
292
293        self.attr5 = None
294        """str: Docstring *after* attribute, with type specified."""
295
296    @property
297    def readonly_property(self):
298        """str: Properties should be documented in their getter method."""
299        return "readonly_property"
300
301    @property
302    def readwrite_property(self):
303        """:obj:`list` of :obj:`str`: Properties with both a getter and setter
304        should only be documented in their getter method.
305
306        If the setter method contains notable behavior, it should be
307        mentioned here.
308        """
309        return ["readwrite_property"]
310
311    @readwrite_property.setter
312    def readwrite_property(self, value):
313        value
314
315    def example_method(self, param1, param2):
316        """Class methods are similar to regular functions.
317
318        Note
319        ----
320        Do not include the `self` parameter in the ``Parameters`` section.
321
322        Parameters
323        ----------
324        param1
325            The first parameter.
326        param2
327            The second parameter.
328
329        Returns
330        -------
331        bool
332            True if successful, False otherwise.
333
334        """
335        return True
336
337    def __special__(self):
338        """By default special members with docstrings are not included.
339
340        Special members are any methods or attributes that start with and
341        end with a double underscore. Any special member with a docstring
342        will be included in the output, if
343        ``napoleon_include_special_with_doc`` is set to True.
344
345        This behavior can be enabled by changing the following setting in
346        Sphinx's conf.py::
347
348            napoleon_include_special_with_doc = True
349
350        """
351        pass
352
353    def __special_without_docstring__(self):
354        pass
355
356    def _private(self):
357        """By default private members are not included.
358
359        Private members are any methods or attributes that start with an
360        underscore and are *not* special. By default they are not included
361        in the output.
362
363        This behavior can be changed such that private members *are* included
364        by changing the following setting in Sphinx's conf.py::
365
366            napoleon_include_private_with_doc = True
367
368        """
369        pass
370
371    def _private_without_docstring(self):
372        pass
373
374
375def foo(var1, var2, *args, long_var_name='hi', **kwargs):
376    r"""Summarize the function in one line.
377
378    Several sentences providing an extended description. Refer to
379    variables using back-ticks, e.g. `var`.
380
381    Parameters
382    ----------
383    var1 : array_like
384        Array_like means all those objects -- lists, nested lists, etc. --
385        that can be converted to an array.  We can also refer to
386        variables like `var1`.
387    var2 : int
388        The type above can either refer to an actual Python type
389        (e.g. ``int``), or describe the type of the variable in more
390        detail, e.g. ``(N,) ndarray`` or ``array_like``.
391    *args : iterable
392        Other arguments.
393    long_var_name : {'hi', 'ho'}, optional
394        Choices in brackets, default first when optional.
395    **kwargs : dict
396        Keyword arguments.
397
398    Returns
399    -------
400    type
401        Explanation of anonymous return value of type ``type``.
402    describe : type
403        Explanation of return value named `describe`.
404    out : type
405        Explanation of `out`.
406    type_without_description
407
408    Other Parameters
409    ----------------
410    only_seldom_used_keywords : type
411        Explanation.
412    common_parameters_listed_above : type
413        Explanation.
414
415    Raises
416    ------
417    BadException
418        Because you shouldn't have done that.
419
420    See Also
421    --------
422    numpy.array : Relationship (optional).
423    numpy.ndarray : Relationship (optional), which could be fairly long, in
424                    which case the line wraps here.
425    numpy.dot, numpy.linalg.norm, numpy.eye
426
427    Notes
428    -----
429    Notes about the implementation algorithm (if needed).
430
431    This can have multiple paragraphs.
432
433    You may include some math:
434
435    .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n}
436
437    And even use a Greek symbol like :math:`\omega` inline.
438
439    References
440    ----------
441    Cite the relevant literature, e.g. [1]_.  You may also cite these
442    references in the notes section above.
443
444    .. [1] O. McNoleg, "The integration of GIS, remote sensing,
445       expert systems and adaptive co-kriging for environmental habitat
446       modelling of the Highland Haggis using object-oriented, fuzzy-logic
447       and neural-network techniques," Computers & Geosciences, vol. 22,
448       pp. 585-588, 1996.
449
450    Examples
451    --------
452    These are written in doctest format, and should illustrate how to
453    use the function.
454
455    >>> a = [1, 2, 3]
456    >>> print([x + 3 for x in a])
457    [4, 5, 6]
458    >>> print("a\nb")
459    a
460    b
461    """
462    # After closing class docstring, there should be one blank line to
463    # separate following codes (according to PEP257).
464    # But for function, method and module, there should be no blank lines
465    # after closing the docstring.
466    pass
467
468
469def invalid_format(test):
470    """
471    In this example, there is no description for the test argument
472
473    Parameters
474    ----------
475    param1
476
477    """
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."""
239
240    def with_traceback(self, object, /):
241        """This method has a changed docstring in Python 3.13+ and is 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.

def with_traceback(self, object, /):
240    def with_traceback(self, object, /):
241        """This method has a changed docstring in Python 3.13+ and is manually added here so that snapshots are consistent."""

This method has a changed docstring in Python 3.13+ and is manually added here so that snapshots are consistent.

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

str: Properties should be documented in their getter method.

readwrite_property
302    @property
303    def readwrite_property(self):
304        """:obj:`list` of :obj:`str`: Properties with both a getter and setter
305        should only be documented in their getter method.
306
307        If the setter method contains notable behavior, it should be
308        mentioned here.
309        """
310        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):
316    def example_method(self, param1, param2):
317        """Class methods are similar to regular functions.
318
319        Note
320        ----
321        Do not include the `self` parameter in the ``Parameters`` section.
322
323        Parameters
324        ----------
325        param1
326            The first parameter.
327        param2
328            The second parameter.
329
330        Returns
331        -------
332        bool
333            True if successful, False otherwise.
334
335        """
336        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):
376def foo(var1, var2, *args, long_var_name='hi', **kwargs):
377    r"""Summarize the function in one line.
378
379    Several sentences providing an extended description. Refer to
380    variables using back-ticks, e.g. `var`.
381
382    Parameters
383    ----------
384    var1 : array_like
385        Array_like means all those objects -- lists, nested lists, etc. --
386        that can be converted to an array.  We can also refer to
387        variables like `var1`.
388    var2 : int
389        The type above can either refer to an actual Python type
390        (e.g. ``int``), or describe the type of the variable in more
391        detail, e.g. ``(N,) ndarray`` or ``array_like``.
392    *args : iterable
393        Other arguments.
394    long_var_name : {'hi', 'ho'}, optional
395        Choices in brackets, default first when optional.
396    **kwargs : dict
397        Keyword arguments.
398
399    Returns
400    -------
401    type
402        Explanation of anonymous return value of type ``type``.
403    describe : type
404        Explanation of return value named `describe`.
405    out : type
406        Explanation of `out`.
407    type_without_description
408
409    Other Parameters
410    ----------------
411    only_seldom_used_keywords : type
412        Explanation.
413    common_parameters_listed_above : type
414        Explanation.
415
416    Raises
417    ------
418    BadException
419        Because you shouldn't have done that.
420
421    See Also
422    --------
423    numpy.array : Relationship (optional).
424    numpy.ndarray : Relationship (optional), which could be fairly long, in
425                    which case the line wraps here.
426    numpy.dot, numpy.linalg.norm, numpy.eye
427
428    Notes
429    -----
430    Notes about the implementation algorithm (if needed).
431
432    This can have multiple paragraphs.
433
434    You may include some math:
435
436    .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n}
437
438    And even use a Greek symbol like :math:`\omega` inline.
439
440    References
441    ----------
442    Cite the relevant literature, e.g. [1]_.  You may also cite these
443    references in the notes section above.
444
445    .. [1] O. McNoleg, "The integration of GIS, remote sensing,
446       expert systems and adaptive co-kriging for environmental habitat
447       modelling of the Highland Haggis using object-oriented, fuzzy-logic
448       and neural-network techniques," Computers & Geosciences, vol. 22,
449       pp. 585-588, 1996.
450
451    Examples
452    --------
453    These are written in doctest format, and should illustrate how to
454    use the function.
455
456    >>> a = [1, 2, 3]
457    >>> print([x + 3 for x in a])
458    [4, 5, 6]
459    >>> print("a\nb")
460    a
461    b
462    """
463    # After closing class docstring, there should be one blank line to
464    # separate following codes (according to PEP257).
465    # But for function, method and module, there should be no blank lines
466    # after closing the docstring.
467    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):
470def invalid_format(test):
471    """
472    In this example, there is no description for the test argument
473
474    Parameters
475    ----------
476    param1
477
478    """

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

Parameters
  • param1