--- tags: numpy --- # How to add examples to NumPy docstrings The number one request from respondents of the NumPy survey for 2020 and 2021 related to documentation has been to have more examples in the documentation. The API reference documentation for NumPy is a mix of hand-written content and generated documentation. One way to decide if this is a generated documentation snippet is to look at the URL. For example: https://numpy.org/devdocs/reference/generated/numpy.shape.html For some documentation pages such as the one above for `numpy.shape`, you can find a link titled `[source]` in the right side of the screen. This leads you to the exact place in the code where the docstring is located, and where it should be altered in case you need to update it or add new examples. For other examples, such as https://numpy.org/devdocs/reference/generated/numpy.ndarray.T.html that link is not available. This is because this docstring may be defined as part of the building process for NumPy. Because many of the internal functions are actually defined in C, as part of compiled extension modules, the docstrings may need to be defined elsewhere. ## How to find the docstrings Let's say we want to improve the documentation for `numpy.ndarray.T`. To find out where this docstring is defined, one option is to search of the existing text in the docstring from the root of the NumPy repo: ``` $ grep -R "The transposed array." ``` By doing this, and excluding the results from the `./doc/build` folder, we see that this text comes up in a file called `_add_newdocs.py`: ``` ./numpy/core/_add_newdocs.py: The transposed array. ``` This file contains almost all the docstrings that are defined for C-extensions, and we [can indeed find the docstring for `numpy.ndarray.T` in there](https://github.com/numpy/numpy/blob/eece996beacc8d78bb48749fe515986ede95bf9e/numpy/core/_add_newdocs.py#L2843). After doing the changes required, we need to rebuild NumPy to see the changes come up in the documentation. ## Good examples Docstring examples should be concise, but descriptive enough to explain the functionality of the object being described. If possible, they should cover corner cases, show all keywords in action and mention the interpretation of results. A general guideline is to have anywhere between one to three examples in docstrings (usually ordered from most simple to more complex ones). This helps readers pick the one closest to their use case. Sometimes it is also useful to mention *why* a specific example is being mentioned, and what it aims to teach or show.