在 python 文档字符串中记录其他函数中可能发生的异常

Rap*_*ipe 5 python documentation docstring exception

在Python中,除了当前函数/方法体中引发的异常之外,我们是否应该在文档字符串中记录可以在其他函数/类中引发的异常?

观察:我正在考虑 Google Python 文档字符串风格https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html

我已经很长时间没有使用 Java 了,但在那里你会明确地说你的方法可以使用“throws”关键字引发什么样的异常。

例如。:

class MyException(Exception):
    pass

class A(object):
    def foo(self):
       """This class does foo

       Returns:
           Int: The number of foo.

       Raises:
            MyException - In case something happen
       """
       if True:
           raise MyException
       return 0

class B(object):
    def __init__(self):
        self._a = A()

    def bar(self):
        """This class does bar
        Returns:
            Int: number of bar
        Raises:
             MyException ????? Should this be here?
        """

        return self._a.foo()
Run Code Online (Sandbox Code Playgroud)

ruo*_*ola 0

是的,您应该记录bar()(和foo()) 可以引发MyException. 这样,对于任何即将使用它的人来说,bar()调用它时可能发生的异常都是显而易见的。