Python 文档字符串:raise 与 raises

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34160968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:32:18  来源:igfitidea点击:

Python Docstring: raise vs. raises

pythondocumentationdocstring

提问by Bob Dylan

I use the PyCharm IDE which assists with crafting PEP0257-compliant docstrings. It provides two attributes I don't entirely understand the distinction/use between:

我使用 PyCharm IDE,它有助于制作符合 PEP0257 的文档字符串。它提供了两个我不完全理解之间的区别/用途的属性:

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

When would I use raiseas opposes to raisesin my docstring? Specifically, if a class required an argument that was not provided and raises a TypeError, which should be used to document that?

我什么时候会在我的文档字符串中使用raiseas 反对raises?具体来说,如果一个类需要一个未提供的参数并引发 a TypeError,应该使用哪个来记录?

采纳答案by erik-e

TL;DR

TL; 博士

raisesis used to describe the possible exceptions being raised. raiseis recognized by Sphinxwhen running autodoc and is the same as raises.

raises用于描述可能引发的异常。在运行 autodoc 时raiseSphinx识别,并且与raises.

Full Explanation

完整说明

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

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

Three which I often use are:

我经常使用的三个是:

  1. NumPy Format
  2. Google Format
  3. Sphinx(much more than a format)
  1. NumPy 格式
  2. 谷歌格式
  3. 狮身人面像(不仅仅是一种格式)

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

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

  1. Simple NumPy
  2. Simple Google
  1. 简单的 NumPy
  2. 简单的谷歌

The implementation for SphinxDocStringwe can see herethere there are numerous keywords which can be recognized. Those tags then link to the list of RAISES_TAGSwhich can be found here.

SphinxDocString我们可以看到这里的实现有很多可以识别的关键字。然后这些标签链接到RAISES_TAGS可在此处找到的列表。

I hope this information is useful.

我希望这些信息有用。

回答by eduardosufan

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

您必须使用raises来描述您的方法/类引发的异常。

:raises:
    Exception: Explanation here.

For example, for a ValueError exception:

例如,对于 ValueError 异常:

:raises:
    ValueError: if fft_data is empty.

回答by Erfan226

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

对于任何感兴趣的人,这对我来说适用于最新版本的 PyCharm。

"""
Some explanations.

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