In the Raises section of the docstring of a function, should the exceptions raised indirectly be listed too?

1.5k views Asked by At

For example, for:

def foo(a):
    if a == 10:
        raise FooError
    return 1 / a

Should the docstring for foo contain something like:

"""Raises:
    FooError: if a is equal to 10.
    ZeroDivisionError: if a is equal to 0.
"""

Or should it just list the exceptions that the function itself raises, i. e. FooError? Any insights as to what's better are welcome, thanks.

1

There are 1 answers

4
MisterMiyagi On BEST ANSWER

TLDR: List all exceptions relevant to users of your code, regardless of implementation.


A docstring is directed at the user of a function/class. Just like a proper class interface, a docstring should not be concerned with implementation details of a function/class. The content of a docstring should only reflect the what, not the how.

This means that whether an error is documented should not differ between different implementations of the same thing.


Consider moving the error-raising code to a helper:

class Bar:
    def foo(self, a):
        if a == 10:
            raise FooBarError
        return 1 / a

    def bar(self, a):
        self._reject(a, 10)
        return 1 / a

    def _reject(self, value, forbidden):
        if value == forbidden:
            raise FooBarError

Both foo and bar are functionally equivalent to client code. Their internal validation logic is a mere implementation detail that does not change how to use them.