#15: Documenting Your Code
With comments in the code we can record our thoughts and considerations that led to our implementation. While this is a great help for developers that need to change the code, it is often not helpful to those who just want to use it - they are drown in detail and miss the big picture. What they need is documentation and luckily for us, Python has a great built-in feature called docstring to solve exactly that problem.
What is a docstring?
A docstring is a string that occurs as the first statement in a module, function, class, or method definition. It is used to document that part of your code and should always use """triple double quotes""":
Why should you use docstrings?
Docstrings look like regular multi-line comments and you can write them that way. But because their specific location at the first line of a function or class, tools like help() can parse them and create a nice documentation:
With just a little change of the position of your comment you are half-way at a documentation. To make your documentation useful and relevant to your audience will be a lot more work.
The __doc__ attribute
Every object in Python has a __doc__ attribute. If a docstring exists, then you can get it in this attribute:
This works for the Python built-in methods and functions as well:
Rules and Formats
In PEP-257 you find the basic rules for docstrings. The most notable one is that multi-line docstrings should end with the """ on their own line.
Different projects came up with additional rules to get a consistent documentation. Aron Manning wrote a nice article on popular docstrings formats that covers NumPy and the Google Style.
Before you reinvent the wheel, look at those formats and see which one you like.
Conclusion
Writing good documentation is hard. At least Python offers you a simple way to put your documentation in your code, so that it will be less effort to keep it to date.