缺少文档字符串的异常 (DOC501)
源自 pydoclint 代码检查器。
此规则不稳定且处于预览状态。使用需要 --preview
标志。
作用
检查函数文档字符串是否记录了所有显式引发的异常。
为什么这不好?
一个函数应该记录在某些情况下直接引发的所有异常。未能记录可能引发的异常可能会误导用户和/或表明文档不完整。
此规则不适用于抽象方法。 对于“存根函数”也会被忽略:即函数体仅包含pass
、...
、raise NotImplementedError
或类似内容。
示例
class FasterThanLightError(ArithmeticError): ...
def calculate_speed(distance: float, time: float) -> float:
"""Calculate speed as distance divided by time.
Args:
distance: Distance traveled.
time: Time spent traveling.
Returns:
Speed as distance divided by time.
"""
try:
return distance / time
except ZeroDivisionError as exc:
raise FasterThanLightError from exc
建议改为
class FasterThanLightError(ArithmeticError): ...
def calculate_speed(distance: float, time: float) -> float:
"""Calculate speed as distance divided by time.
Args:
distance: Distance traveled.
time: Time spent traveling.
Returns:
Speed as distance divided by time.
Raises:
FasterThanLightError: If speed is greater than the speed of light.
"""
try:
return distance / time
except ZeroDivisionError as exc:
raise FasterThanLightError from exc