Documenting your API
Before generating our documentation with Sphinx we need to document our code.
Open the file sphinx.py
. We are going to add Python docstrings to the class Sphinx
. In this tutorial we will follow the Google-style docstring. You can browse examples of this style here.
Sphinx docstrings are traditionally written in reStructuredText
, but they are much more dense and hard to read. The Google-style docstring is friendlier to the eye while browsing the source code.
Locate the method check_riddle_answer()
and add a Google-style docstring to document it:
def check_riddle_answer(self, answer: str, return_hint: bool = False) -> str:
"""Evaluates the given answer to the riddle.
Args:
answer (str): The given answer to the riddle.
return_hint (bool, optional): Controls whether a hint for the riddle should
be returned. Defaults to False.
Raises:
IncorrectAnswer: Exception for incorrect answer.
Returns:
str: The result of the evaluation of the answer.
"""
In VS Code, you can install the extension autoDocstring
which will generate python docstring prompts, so you only need to fill them in. PyCharm supports this as well.
Continue adding documentation for the rest of the methods in sphinx.py
and for the class itself. Repeat for riddle.py
.
You can get some inspiration of how we would complete sphinx.py
and riddle.py
.
When youโre done, commit the changes you made:
# from the project root
git add src/sphinxy/sphinx.py src/sphinxy/riddle.py
git commit -m "Added docstrings"
git push origin main
๐ You have now reached the 04-document-api
part of the tutorial. If not, check out that branch and continue from there.
Previous: reStructuredText basics Next: Generating HTML docs from docstrings