【python】Google 风格和 Numpy 风格 docstring

Google style and NumPy style are two conventions for writing docstrings in Python. They are designed to be readable and to work well with documentation generation tools like Sphinx. These styles provide guidelines on how to format documentation so that it can be parsed by tools like Sphinx and presented in a structured and consistent manner.

Google Style Docstrings

Google style docstrings are more verbose than some other styles and are often preferred for their readability. Here’s an example of a Google style docstring:

def function(arg1, arg2):
"""Summary of the function.

Extended description can be in multiple paragraphs if necessary.

Args:
arg1 (int): Description of arg1.
arg2 (str): Description of arg2.

Returns:
bool: Description of return value.

Raises:
ValueError: Explanation of when a ValueError is raised.
"""
pass

Key points:

  • A one-line summary that does not start with a variable name or an imperative verb.
  • A blank line follows the summary.
  • The “Args” section describes each parameter with its name, type, and description.
  • The “Returns” section describes the return type and purpose.
  • The “Raises” section lists any exceptions that the function might raise.

NumPy Style Docstrings

NumPy style docstrings are similar to Google style but have some differences in formatting, particularly in how they handle parameter and return value documentation. They are widely used in scientific and mathematical Python communities. Here’s an example of a NumPy style docstring:

def function(arg1, arg2):
"""
Summary of the function.

Extended description can be in multiple paragraphs if necessary.

Parameters
----------
arg1 : int
Description of arg1.
arg2 : str
Description of arg2.

Returns
-------
bool
Description of return value.

Raises
------
ValueError
Explanation of when a ValueError is raised.
"""
pass

Key points:

  • A one-line summary followed by an optional extended description.
  • The “Parameters” section is marked with a header and a dashed line.
  • Each parameter is listed with its name, type, and description.
  • The “Returns” section is similar, with a header, dashed line, and a description.
  • The “Raises” section lists exceptions in the same way.

Both styles are well supported by Sphinx, especially when used in combination with the Sphinx extension napoleon. The napoleon extension allows Sphinx to parse both Google style and NumPy style docstrings into the reStructuredText format that Sphinx uses to generate documentation.

When choosing between these styles, consider the conventions used in your project or community and your personal preference for readability and clarity.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值