📅  最后修改于: 2023-12-03 15:18:03.303000             🧑  作者: Mango
NumPy-style docstrings are a way of documenting your Python code in a standardized, machine-readable format that is easy to read and parse. They are named after the widely-used NumPy library, which popularized this style of documentation.
In this guide, we'll explain what NumPy-style docstrings are, why you should use them, and how to write them.
NumPy-style docstrings are a variant of Google-style docstrings that use a structured format for describing your code. They consist of three main sections:
Here's an example:
def square(x):
"""
Return the square of a number.
Parameters
----------
x : int or float
The number to square.
Returns
-------
float
The square of `x`.
"""
return x ** 2
In this example, the summary line briefly describes what the function does, while the parameters and returns sections provide more detailed information about the inputs and outputs of the function.
NumPy-style docstrings have several advantages over other forms of documentation:
Here are some tips for writing effective NumPy-style docstrings:
Here's an example of a more complex NumPy-style docstring:
def fibonacci(n):
"""
Calculate the Fibonacci series.
Compute the nth Fibonacci number, where:
* Fibonacci(0) = 0
* Fibonacci(1) = 1
* Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
Parameters
----------
n : int
The index of the Fibonacci number to compute.
Returns
-------
int
The nth Fibonacci number.
Examples
--------
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
"""
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
In this example, we use the NumPy-style docstring format to describe the parameters and returns of the fibonacci
function, as well as providing examples of how to use it.
NumPy-style docstrings are a powerful tool for documenting your Python code. By using a standardized format, you can ensure that your documentation is consistent, easy to read, and machine-readable. Follow the guidelines outlined in this guide to write effective NumPy-style docstrings for your own projects.