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 explicitly raise.
Consider the function
def inv(a):
if a == 0:
raise ZeroDivisionError
else:
return 1/a
So in a docstring under the "Raises" keyword I would definetly put ZeroDivisionError. However, depending on the input I would also expect a TypeError. So would you put that also in the docstring?
Due to the EAFP principle (if i understand it correctly) I don't want to check for types here, correct? Any hint (also on the code sample) is welcome.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With