Should the docstring only contain the exceptions that are explicitly raised by a function?

前端 未结 2 1099
别那么骄傲
别那么骄傲 2021-02-20 15:36

When writing doc strings in python, I am wondering if the docstring should contain the exceptions that are implicitly raised or if it should also contain the exceptions I explic

2条回答
  •  没有蜡笔的小新
    2021-02-20 15:57

    It depends what (or whom) you're writing the docstring for. For automatic conversion to API documentation, I like Google-style docstrings, which would look like:

    def inv(a):
        """Return the inverse of the argument.
    
        Arguments:
          a (int): The number to invert.
    
        Returns:
          float: The inverse of the argument.
    
        Raises:
          TypeError: If 1 cannot be divided by the argument.
          ZeroDivisionError: If the argument is zero.
    
        """
        return 1 / a
    

    Here I've included all of the exceptions that the function is likely to raise. Note that there's no need to explicitly raise ZeroDivisionError - that will happen automatically if you try to divide by zero.


    However, if you aren't creating documentation from the docstring, I would probably just include the description line for such a simple function:

    def inv(a):
        """Return the inverse of the argument."""
        return 1 / a 
    

    Anyone using it is likely to know that you can't invert e.g. strings.


    I don't want to check for types here, correct?

    I wouldn't - if the user, after reading your documentation, decides to pass e.g. a string into the function they should expect to get the TypeError, and there's no point testing the argument type to then raise the same exception yourself that the code would have raised anyway (again, see also the ZeroDivisionError!) That is, unless e.g. float or complex numbers should be invalid input, in which case you will need to handle them manually.

提交回复
热议问题