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

前端 未结 2 1088
别那么骄傲
别那么骄傲 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:53

    No. The docstring should describe the input expected. If this were my function, I would include something like this in the docstring:

    """Return the inverse of an integer.  ZeroDivisionError is raised if zero is
    passed to this function."""
    

    Therefore it is specified that the input should be an integer. Specifying that the function can raise a TypeError just overly complicates the docstring.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题