Python Docstrings
6 min read ·
Python does not have many different types of comments like some programming languages. However, Python developers follow several conventions for documenting code effectively.
Docstrings
""" """) or triple single quotes (''' ''').Output
Use docstrings to explain the purpose of functions, classes, and modules. Use comments to explain complex logic inside the code.
Accessing a Docstring
__doc__ attribute.Output
Module Docstrings
Output
Function Docstrings
Output
Class Docstrings
Output
Multi Line Docstrings
TODO Comments
FIXME Comments
NOTE Comments
HACK Comments
Why Triple Quoted Strings Are Not Comments
Output
Triple quoted strings should not replace regular comments. Use them primarily for docstrings.
When Should You Write Comments?
- Explaining complex calculations.
- Describing business rules.
- Documenting unusual algorithms.
- Explaining important design decisions.
- Recording assumptions made in the code.
- Leaving reminders for future improvements.
Example of Bad Comments
Example of Good Comments
Comments vs Docstrings
| Feature | Comments | Docstrings |
|---|---|---|
| Starts With | # | """ """ or ''' ''' |
| Executed | Ignored | Stored as documentation |
Accessible Using __doc__ | No | Yes |
| Purpose | Explain code | Document modules, classes, and functions |
| Used By Documentation Tools | No | Yes |
Common Mistakes
Using Comments Instead of Clear Variable Names
Writing Long Paragraphs as Comments
Forgetting to Update Comments
Using Triple Quotes Everywhere
# symbol.Never rely on outdated comments. Incorrect comments can mislead developers and introduce bugs during maintenance.
Best Practices
- Write comments only when they provide useful information.
- Write docstrings for every public function, class, and module.
- Explain why the code exists instead of what every line does.
- Keep comments short, meaningful, and up to date.
- Use TODO and FIXME comments only when necessary.
- Prefer descriptive variable and function names over excessive comments.
- Follow a consistent commenting style throughout your project.
You now understand advanced Python commenting techniques, including docstrings, TODO comments, FIXME comments, module documentation, function documentation, class documentation, and professional commenting practices used in real world Python projects.
Exercise
- Create a function with a docstring.
- Print a function's docstring using the
__doc__attribute. - Write a module docstring.
- Create a class with a docstring.
- Add a TODO comment to your program.
- Add a FIXME comment.
- Replace an unnecessary comment with a meaningful variable name.
- Write a multi line docstring for a function that calculates the area of a rectangle.
Challenge
- Add a module docstring describing the program.
- Create a class with a class docstring.
- Create two functions, each with its own docstring.
- Add one TODO comment.
- Add one FIXME comment.
- Print one function's docstring using the
__doc__attribute.