Python Documentation: Getting Started
Many of us Pythonistas have wished to publish our own modules on Pip for everyone else to download and use. While writing the code/logic as python script is straightforward, the real hassle is actually formatting your code for publishing, adding documentation and publishing to PyPi and Documentation servers.
In this will be a multi-series, I will try to collate all the tools / commands required enabling us to build and publish your packages. In first series, we will cover the documentation of the Python Modules: walking you through creating the documentation, generating HTML using Sphinx and hosting it at ReadTheDocs.
Focusing on Documentation first rather than the module itself might sound weird, but ‘ A good Python Module is unusable without a Great Documentation!’. So hold on tight…
Creating the documentation
We will be using PyCharm to create our documentation. PyCharm provides a good integration to auto-generate the Docstring template for our functions, etc.
First, we will need to setup our doc-string format. Goto PyCharm > Preferences > Tools > Python Integrated Tools > Docstrings
I prefer Google Docstring format, you are free to choose anyone to your preference. You can get a brief idea about different formats here
Now, you can start documenting your code. To document your function add a new line below your function start and enter triple quotes (“““\n”””) and press enter. This will generate the template docstring for your function
All the docstrings should be added inside triple quotes and directly following the function / class / module start. Stick to this format, as in later parts we will be using these triple-quote docstrings to generate HTML / PDF documentation for our module
Docstring guidelines
Although you are free to write whatever and however you want to, but following some general guidelines will help you develop detailed and consistent documentation for your module:
- Brief one-liner description of the function
- Detailed explanation of the algorithm
- Usage syntax and class parameters for the classes
- Data types of the function parameters
- Exceptions and Return values
The documentation build tools follow ReStructured Text syntax. You can add more details, code-blocks, TODO comments, Hyperlinks, etc. in your docstrings using the RST syntax.
One can also add some basic function syntax test using doctest
In next part, we will look at generating HTML files from our Docstrings using Sphinx
For more details and resources, you can go through following resources