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.
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:
Both
foo
andbar
are functionally equivalent to client code. Their internal validation logic is a mere implementation detail that does not change how to use them.