3 Different Docstring Formats for Python
A quick walkaround of Google, NumPy, and Sphinx docstrings
Python is becoming a popular programming language nowadays. For any coding project, documentation is the most important part for increasing the readability of code but at the same time most ignored part too! To solve this, the Sphinx tool comes in handy which automates the documentation part, if you aren’t aware of this tool, have a look at this.
Now that you’re aware of Sphinx and know how to use it. Let us know the most commonly used docstring formats out there in the wild, which are namely- Google, NumPy, and Sphinx docstring formats.
1. Google Docstring
This docstring format is recommended by Khan Academy and is popularly known as “Google Docstring”. To make sure the docstring is compatible with Sphinx and is recognized by Sphinx’s autodoc, add the sphinx.ext.napoleon
extension in the conf.py
file. The docstring format is:
The output generated by Sphinx looks like this:

To make life easier if you’re using VS Code, you can install this extension. This extension lays the boilerplate for the docstrings and you only need to add the description of each parameter.
2. NumPy Docstring
This documentation format is used in major data science libraries like NumPy, SciPy, and Pandas. Just like Google’s docstring, to make it compatible with Sphinx you’ve to add the sphinx.ext.napoleon
extension in the conf.py
file. The format for docstring is:
The output for the same is:

Google Vs NumPy’s Docstrings:
The output for both docstrings looks similar, the main difference between the two styles is that Google uses indentation to separate sections, whereas NumPy uses underlines. NumPy style tends to require more vertical space, whereas Google-style tends to use more horizontal space. Google-style tends to be easier to read for short and simple docstrings, whereas NumPy-style tends to be easier to read for long and in-depth docstrings.
3. Sphinx Docstring
Nothing better than the good old sphinx docstring, this is the most basic docstring format that is used but is somewhat visually dense which makes it hard to read. The format for the same is:
The output looks like this:

To experiment with the different formats, clone this repository. Once cloned, play around with the formats and run themake clean html
followed by make html
inside of docs folder to regenerate the HTML files.
Conclusion
Other than the above formats, there are many docstring formats that can be used for Python and we don’t have a single winner in this game.
So choose whichever format you’re comfortable with, do not mix the formats, and stick with it throughout the project. My personal favorite is NumPy’s Docstring!