# # 一份给NumPy/SciPy的文档做贡献的指南

Sphinx与numpy约定结合使用时，应使用numpydoc扩展名，以便正确处理文档字符串。例如，Sphinx Parameters将从您的docstring中提取该 部分并将其转换为字段列表。使用numpydoc也将避免普通Sphinx在遇到-------------像sphinx期望在文档字符串中找到的节标题（例如）之类的numpy docstring约定时产生的reStructuredText错误。

import numpy.fft


np.fft.fft2(...)


## # numpydoc docstring指南

### # 导入约定

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt


### # 文档串标准

"""This is the form of a docstring.

It can be spread over several lines.

"""


NumPy，SciPy和scikits遵循文档字符串的通用约定，提供一致性，同时还允许我们的工具链生成格式良好的参考指南。本文档描述了当前社区对此类标准的共识。如果您有改进建议，请将它们发布在numpy-discussion列表中

### # 章节

docstring由标题分隔的许多部分组成（弃用警告除外）。每个标题应以连字符加下划线，并且章节顺序应与下面的描述一致。

1. Short summary

A one-line summary that does not use variable names or the function name, e.g.

def add(a, b):
"""The sum of two numbers.

"""


The function signature is normally found by introspection and displayed by the help function. For some functions (notably those written in C) the signature is not available, so we have to specify it as the first line of the docstring:

"""

The sum of two numbers.

"""

2. Deprecation warning

A section (use if applicable) to warn users that the object is deprecated. Section contents should include:

• In what NumPy version the object was deprecated, and when it will be removed.
• Reason for deprecation if this is useful information (e.g., object is superseded, duplicates functionality found elsewhere, etc.).
• New recommended way of obtaining the same functionality.

This section should use the deprecated Sphinx directive instead of an underlined section header.

.. deprecated:: 1.6.0
ndobj_old will be removed in NumPy 2.0.0, it is replaced by
ndobj_new because the latter works also with array subclasses.

3. Extended Summary

A few sentences giving an extended description. This section should be used to clarify functionality, not to discuss implementation detail or background theory, which should rather be explored in the Notes section below. You may refer to the parameters and the function name, but parameter descriptions still belong in the Parameters section.

4. Parameters

Description of the function arguments, keywords and their respective types.

Parameters
----------
x : type
Description of parameter x.
y
Description of parameter y (with type not specified)


Enclose variables in single backticks. The colon must be preceded by a space, or omitted if the type is absent.

For the parameter types, be as precise as possible. Below are a few examples of parameters and their types.

Parameters
----------
filename : str
copy : bool
dtype : data-type
iterable : iterable object
shape : int or tuple of int
files : list of str


If it is not necessary to specify a keyword argument, use optional:

x : int, optional


Optional keyword parameters have default values, which are displayed as part of the function signature. They can also be detailed in the description:

Description of parameter x (the default is -1, which implies summation
over all axes).


When a parameter can only assume one of a fixed set of values, those values can be listed in braces, with the default appearing first:

order : {'C', 'F', 'A'}
Description of order.


When two or more input parameters have exactly the same type, shape and description, they can be combined:

x1, x2 : array_like
Input arrays, description of x1, x2.

5. Returns

Explanation of the returned values and their types. Similar to the Parameters section, except the name of each return value is optional. The type of each return value is always required:

Returns
-------
int
Description of anonymous integer return value.


If both the name and type are specified, the Returns section takes the same form as the Parameters section:

Returns
-------
err_code : int
Non-zero value indicates error code, or zero on success.
err_msg : str or None
Human readable error message, or None on success.
Yields


Explanation of the yielded values and their types. This is relevant to generators only. Similar to the Returns section in that the name of each value is optional, but the type of each value is always required:

Yields
------
int
Description of the anonymous integer return value.


If both the name and type are specified, the Yields section takes the same form as the Returns section:

Yields
------
err_code : int
Non-zero value indicates error code, or zero on success.
err_msg : str or None
Human readable error message, or None on success.


Support for the Yields section was added in numpydoc version 0.6.

Explanation of parameters passed to a generator’s .send() method, formatted as for Parameters, above. Since, like for Yields and Returns, a single object is always passed to the method, this may describe either the single parameter, or positional arguments passed as a tuple. If a docstring includes Receives it must also include Yields.

7. Other Parameters

An optional section used to describe infrequently used parameters. It should only be used if a function has a large number of keyword parameters, to prevent cluttering the Parameters section.

8. Raises

An optional section detailing which errors get raised and under what conditions:

Raises
------
LinAlgException
If the matrix is not numerically invertible.


This section should be used judiciously, i.e., only for errors that are non-obvious or have a large chance of getting raised.

9. Warns

An optional section detailing which warnings get raised and under what conditions, formatted similarly to Raises.

10. Warnings

An optional section with cautions to the user in free text/reST.

An optional section used to refer to related code. This section can be very useful, but should be used judiciously. The goal is to direct users to other functions they may not be aware of, or have easy means of discovering (by looking at the module docstring, for example). Routines whose docstrings further explain parameters used by this function are good candidates.

As an example, for numpy.mean we would have:

See Also
--------
average : Weighted average


When referring to functions in the same sub-module, no prefix is needed, and the tree is searched upwards for a match.

Prefix functions from other sub-modules appropriately. E.g., whilst documenting the random module, refer to a function in fft by

fft.fft2 : 2-D fast discrete Fourier transform


When referring to an entirely different module:

scipy.random.norm : Random variates, PDFs, etc.


Functions may be listed without descriptions, and this is preferable if the functionality is clear from the function name:

See Also
--------
func_a : Function a with its description.
func_b, func_c_, func_d
func_e

12. Notes

An optional section that provides additional information about the code, possibly including a discussion of the algorithm. This section may include mathematical equations, written in LaTeX format:

The FFT is a fast implementation of the discrete Fourier transform:

.. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n}


Equations can also be typeset underneath the math directive:

The discrete-time Fourier time-convolution property states that

.. math::

x(n) * y(n) \Leftrightarrow X(e^{j\omega } )Y(e^{j\omega } )\\
another equation here


Math can furthermore be used inline, i.e.

The value of :math:\omega is larger than 5.


Variable names are displayed in typewriter font, obtained by using \mathtt{var}:

We square the input parameter alpha to obtain
:math:\mathtt{alpha}^2.


Note that LaTeX is not particularly easy to read, so use equations sparingly.

Images are allowed, but should not be central to the explanation; users viewing the docstring as text must be able to comprehend its meaning without resorting to an image viewer. These additional illustrations are included using:

.. image:: filename


where filename is a path relative to the reference guide source directory.

13. References

References cited in the notes section may be listed here, e.g. if you cited the article below using the text [1]_, include it as in the list as follows:

.. [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.


which renders as [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.

Referencing sources of a temporary nature, like web pages, is discouraged. References are meant to augment the docstring, but should not be required to understand it. References are numbered, starting from one, in the order in which they are cited.

Warning

References will break tables

Where references like [1] appear in a tables within a numpydoc docstring, the table markup will be broken by numpydoc processing. See numpydoc issue #130

14. Examples

An optional section for examples, using the doctest format. This section is meant to illustrate usage, not to provide a testing framework – for that, use the tests/ directory. While optional, this section is very strongly encouraged.

When multiple examples are provided, they should be separated by blank lines. Comments explaining the examples should have blank lines both above and below them:

>>> np.add(1, 2)
3

Comment explaining the second example

>>> np.add([1, 2], [3, 4])
array([4, 6])


The example code may be split across multiple lines, with each line after the first starting with ‘… ‘:

>>> np.add([[1, 2], [3, 4]],
...        [[5, 6], [7, 8]])
array([[ 6,  8],
[10, 12]])


For tests with a result that is random or platform-dependent, mark the output as such:

>>> import numpy.random
>>> np.random.rand(2)
array([ 0.35773152,  0.38568979])  #random


You can run examples as doctests using:

>>> np.test(doctests=True)
>>> np.linalg.test(doctests=True)  # for a single module


In IPython it is also possible to run individual examples simply by copy-pasting them in doctest mode:

In [1]: %doctest_mode
Exception reporting mode: Plain
Doctest mode is: ON
>>> %paste
import numpy.random
np.random.rand(2)
## -- End pasted text --
array([ 0.8519522 ,  0.15492887])


It is not necessary to use the doctest markup <BLANKLINE> to indicate empty lines in the output. Note that the option to run the examples through numpy.test is provided for checking if the examples work, not for making the examples part of the testing framework.

The examples may assume that import numpy as np is executed before the example code in numpy. Additional examples may make use of matplotlib for plotting, but should import it explicitly, e.g., import matplotlib.pyplot as plt. All other imports, including the demonstrated function, must be explicit.

When matplotlib is imported in the example, the Example code will be wrapped in matplotlib’s Sphinx plot directive <http://matplotlib.org/sampledoc/extensions.html>_. When matplotlib is not explicitly imported, plot:: can be used directly if matplotlib.sphinxext.plot_directive is loaded as a Sphinx extension in conf.py.

### # Documenting 类

#### # 类文档字符串

Attributes
----------
x : float
The X coordinate.
y : float
The Y coordinate.


Attributes
----------
real
imag
x : float
The X coordinate
y : float
The Y coordinate


class Photo(ndarray):
"""
Array with associated photographic information.

...

Attributes
----------
exposure : float
Exposure in seconds.

Methods
-------
colorspace(c='rgb')
Represent the photo in the given colorspace.
gamma(n=1.0)
Change the photo's gamma exposure.

"""


### # 记录类实例

np，c_np.index_exp 等）可能需要一些小心。要为这些实例提供有用的文档字符串，我们执行以下操作：

• 单实例：如果只公开一个类的实例，请记录该类。示例可以使用实例名称。
• 多个实例：如果公开了多个实例，则会__doc__在运行时写入每个实例的文档字符串并将其分配给实例的 属性。该类按常规进行记录，并且可以在NotesSee Also 部分中提及公开的实例。

### # 记录常量

1. summary
2. extended summary (optional)
4. references (optional)
5. examples (optional)


### # 记录模块

1. summary
2. extended summary
3. routine listings
5. notes
6. references
7. examples


### # 其他要记住的要点

• 等式：如上面的注释部分所述，LaTeX格式应保持最小。通常可以将方程式显示为Python代码或伪代码，这在终端中更易读。对于内联显示器，请使用双反键（如）。要在上方和下方显示空行，请使用双冒号并缩进代码，例如：y = np.sin(x)
end of previous sentence::

y = np.sin(x)

• 注释和警告：如果文档字符串中的某些点值得特别强调，则可以在警告的上下文附近（部分内部）使用注释或警告的reST指令。句法：
.. warning:: Warning text.

.. note:: Note text.


• array_like：对于带有不仅可以有 ndarray 类型的参数的函数，还有可以转换为ndarray的类型（即标量类型，序列类型），可以使用 array_like 类型记录这些参数。
• 链接：如果您需要在docstring中包含超链接，请注意某些文档字符串部分未被解析为标准reST，并且在这些部分中，numpydoc可能会被超链接目标混淆，例如：
.. _Example: http://www.example.com


Example <http://www.example.com>_