Qui*_*2k1 9 python docstring raise python-3.x
在python中编写doc字符串时,我想知道docstring是否应该包含隐式引发的异常,或者它是否还应该包含我明确提出的异常.
考虑这个功能
def inv(a):
if a == 0:
raise ZeroDivisionError
else:
return 1/a
Run Code Online (Sandbox Code Playgroud)
因此,在"Raises"关键字下的文档字符串中,我肯定会放置ZeroDivisionError.但是,根据输入,我也会期望TypeError.那么你也会把它放在docstring中吗?
由于EAFP原则(如果我理解正确),我不想在这里检查类型,对吗?任何提示(也在代码示例上)都是受欢迎的.
这取决于你为什么(或谁)编写文档字符串.要自动转换为API文档,我喜欢Google风格的文档字符串,它们看起来像:
def inv(a):
"""Return the inverse of the argument.
Arguments:
a (int): The number to invert.
Returns:
float: The inverse of the argument.
Raises:
TypeError: If 1 cannot be divided by the argument.
ZeroDivisionError: If the argument is zero.
"""
return 1 / a
Run Code Online (Sandbox Code Playgroud)
在这里,我已经包含了该函数可能引发的所有异常.请注意,没有必要明确raise ZeroDivisionError- 如果您尝试除以零,将自动发生.
但是,如果您不是从docstring创建文档,我可能只包含这样一个简单函数的描述行:
def inv(a):
"""Return the inverse of the argument."""
return 1 / a
Run Code Online (Sandbox Code Playgroud)
使用它的任何人都可能知道你不能反转例如字符串.
我不想在这里检查类型,对吗?
我不会-如果用户阅读您的文件后,决定通过如串入功能,他们应该期望得到的TypeError,而且也没有一点测试参数类型,然后提出同样的异常你自己的代码将有无论如何都提出了(再次,也参见ZeroDivisionError!)即,除非eg float或complex数字应该是无效输入,在这种情况下你需要手动处理它们.
不。文档字符串应该描述预期的输入。如果这是我的函数,我会在文档字符串中包含类似的内容:
"""Return the inverse of an integer. ZeroDivisionError is raised if zero is
passed to this function."""
Run Code Online (Sandbox Code Playgroud)
因此指定输入应为整数。指定该函数可以引发 aTypeError只是使文档字符串变得过于复杂。