I use the PyCharm IDE which assists with crafting PEP0257-compliant docstrings. It provides two attributes I don't entirely understand the distinction/use between:
:raise Exception: exception explanation here
:raises Exception: exception explanation here
When would I use raise
as opposes to raises
in my docstring? Specifically, if a class required an argument that was not provided and raises a TypeError
, which should be used to document that?
The class constructor should be documented in the docstring for its __init__ method. This is quite logical, as this is the usual procedure for functions and methods, and __init__() is not an exception. As a consequence, this puts the code and its documentation in the same place, which helps maintenance.
As mentioned above, Python docstrings are strings used right after the definition of a function, method, class, or module (like in Example 1). They are used to document our code. We can access these docstrings using the __doc__ attribute.
A Python docstring is a string used to document a Python module, class, function or method, so programmers can understand what it does without having to read the details of the implementation. Also, it is a common practice to generate online (html) documentation automatically from docstrings.
Handling Docstring IndentationAny indentation in the first line of the docstring (i.e., up to the first newline) is insignificant and removed. Relative indentation of later lines in the docstring is retained. Blank lines should be removed from the beginning and end of the docstring.
TL;DR
raises
is used to describe the possible exceptions being raised. raise
is recognized by Sphinx when running autodoc and is the same as raises
.
Full Explanation
PyCharm helps in using a few different styles of docstring comments.
Three which I often use are:
In all of these there is a special section for Raises
which you can see in an older version of the PyCharm code tests:
The implementation for SphinxDocString
we can see here there there are numerous keywords which can be recognized. Those tags then link to the list of RAISES_TAGS
which can be found here.
I hope this information is useful.
You must use raises
to describe exceptions raised by your method/class.
:raises: Exception: Explanation here.
For example, for a ValueError exception:
:raises: ValueError: if fft_data is empty.
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