Python Docstring: 加薪 vs

我使用 PyCharmIDE 来帮助创建符合 PEP0257的文档字符串。它提供了两个属性,我不完全理解它们之间的区别/用法:

  • :raise Exception: exception explanation here
  • :raises Exception: exception explanation here

什么时候在文档字符串中使用 raise而不是 raises?具体来说,如果一个类需要一个没有提供的参数并引发一个 TypeError,那么应该使用哪个参数来记录这个参数?

50336 次浏览

TL;DR

raises is used to describe the possible exceptions being raised. raise is recognized by Sphinx when running autodoc and is the same as raises.

Full Explanation

PyCharm helps in using a few different styles of docstring comments.

Three which I often use are:

  1. NumPy Format
  2. Google Format
  3. Sphinx (much more than a format)

In all of these there is a special section for Raises which you can see in an older version of the PyCharm code tests:

  1. Simple NumPy
  2. Simple Google

The implementation for SphinxDocString we can 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.

I hope this information is useful.

You must use raises to describe exceptions raised by your method/class.

:raises:
Exception: Explanation here.

For example, for a ValueError exception:

:raises:
ValueError: if fft_data is empty.

This works for me in latest version of PyCharm for anyone interested.

"""
Some explanations.


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