I'm not going to focus much on the syntax. Instead I rather explain principles I used to guide me. Python is 30 years old and there are artifacts of the language should probably go away.
"Code is more often read than written." - Guido Van Rossum, Creator of Python
When I learn and distill information, it's helpful for me to write a one sentence description and to category when and where to use things.
What is the purpose of each type of doc element?
- Doctests: Allows you to embed testable code snippets which seems essential in the early days of Python. Stylistically, this is not a great way to document, so use it sparingly.
- Docstrings: Should always be use for public classes, modules, and functions. Not required for non-public but you should describe each method.
- NumPy style docstrings: Provides a structured and highly verbose style to document multi-paragraph annotations, parameters, return values, and links to documentation. For me this is a super class of docstrings. Suggested for AI and ML projects, open source projects, and scientific applications.
- Block comments - generally apply to some or all of the code that follows.
- Inline Comments
- Tagging Comments: Adding comments that are suggestions or meant to imply future work: #BUG, #TODO, #Deprecated: remove in the future.
Documenting vs. Commenting
When code is concise and well structured, reading code tells you how it works.
Comments should explain why you've written this code.
- Comments describe code for other developers
- Makes extending and maintaining the code easier.
- Helps the reader build a mental model of the code by describing the purpose and design.
# What business rule you implemented? def display_name(): # Policy to use title and full name of customer. return "President Abraham Lincoln" # Why did you made this decision? def utc_now(): # All datetime values must be TZ aware and set UTC timezone. return datetime.now(pytz.utc) @functools.lru_cache(maxsize=128) def expensive_computation(): # Creates a small in memory cache to reused O(n^3) computation ...
- Describes code use and functionality to users
- May aid further development of code, but intended audience is users (both actual and potential) of the code.
A single line of code can be just as inscrutable as a thousand lines of code. Bad documentation is just as harmful as no documentation. There will never be a perfect or scientifically provable method for creating software.
It's on us to accept that most aspects of software development is subjective. Errors exist. There is no right way to program.