4

In Python, should we document in the docstrings exceptions that can be raised in other functions/classes besides the ones that are raised in the body of current function/method?

Obs.: I'm considering the Google Python docstring style https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html

It has been a long time since I don't play with Java, but there you would explicitly say what kind of exceptions that your method could raise with the "throws" keyword.

Eg.:

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()
Raphael Philipe
  • 171
  • 2
  • 5
  • 2
    If you’re trying to document every exception your function can throw, then yes, you should include functions that can be thrown through your function by stuff that you call. Otherwise, your list is not only useless, but misleading. – abarnert Aug 23 '18 at 21:29
  • 3
    If you think about this with concrete cases instead of abstract and meaningless ones, this becomes obvious. For example, if you call my `distance` function, and it documents that it can raise a bunch of different exceptions but not a DivideByZero, you’re going to take that to mean you will never get a DivideByZero from calling my function. If you get one, it doesn’t matter that it originally came from some other function that my function called; my function is broken. – abarnert Aug 23 '18 at 21:33
  • The one exception to that rule is if you pass in a callback function, and I call your callback, and you raise some exception I never heard of, I may or may not pass that through to you. Either way is probably acceptable, but in that case is probably document whichever I chose, by adding something like “and any exceptions raised by the callback argument” to the end of the list. – abarnert Aug 23 '18 at 21:34
  • Does this answer your question? [Should the docstring only contain the exceptions that are explicitly raised by a function?](https://stackoverflow.com/questions/33262919/should-the-docstring-only-contain-the-exceptions-that-are-explicitly-raised-by-a) – Jacob Pavlock Sep 08 '20 at 15:11

1 Answers1

0

Yes, you should document that bar() (and foo()) can raise a MyException. This way it's immediately obvious for anyone who's about to use bar() that which exceptions can occur when calling it.

ruohola
  • 21,987
  • 6
  • 62
  • 97