Python 文档字符串:加薪与加薪

Python Docstring: raise vs. raises

我使用 PyCharm IDE 来帮助制作符合 PEP0257 的文档字符串。它提供了两个我不完全理解的属性 distinction/use 之间:

我什么时候会在文档字符串中使用 raise 而不是 raises?具体来说,如果 class 需要一个未提供的参数并引发 TypeError,应该使用它来记录?

TL;DR

raises 用于描述可能引发的异常。 raise 在 运行 autodoc 时被 Sphinx 识别,与 raises.

相同

完整说明

PyCharm 有助于使用几种不同风格的文档字符串注释。

我经常使用的三个是:

  1. NumPy Format
  2. Google Format
  3. Sphinx(不仅仅是一种格式)

在所有这些中,有一个特殊的部分用于 Raises,您可以在旧版本的 PyCharm 代码测试中看到它:

  1. Simple NumPy
  2. Simple Google

SphinxDocString 的实现我们可以see here there there are numerous keywords which can be recognized. Those tags then link to the list of RAISES_TAGS which can be found here

希望这些信息有用。

您必须使用 raises 来描述您的 method/class 引发的异常。

:raises:
    Exception: Explanation here.

例如,对于 ValueError 异常:

:raises:
    ValueError: if fft_data is empty.

任何感兴趣的人都可以在最新版本的 PyCharm 中使用。

"""
Some explanations.

:raises WhatEverError: if there is any error
"""