Work in Progress
A common request in /r/learnpython is for a review of existing code. While I have no intention of discouraging that practice, 90% of submissions include the same, basic issues. This is a list of those most common issues along with an attempt to elaborate on the issue and possible solutions.
Comments should be rare in Python code. For the most part, Python code is (or should be) readable enough that no description is necessary. MOST comments found in beginner code should be Docstrings instead (more below).
The exceptions are where the code is incomplete, is dealing with an unusual, external limitation, or where some "cleverness" was used. In this case, simply acknowleding the non-Pyhonic nature of the code and why it was necessary is enough. If a long description feels necessary, instead summarize and link to or reference a more exhaustive document.
-
students = [] # A list of students
Completely obvious due to the fact that the variable is named "students" and it is initialized to a list.
-
## Constants
It's good to group your constants together, but that should be obvious by their formatting. See PEP8 for more details.
-
# For /reasons/, this request almost always fails the first time, so we try up to twice. # If the second request fails, something is really wrong.`
-
# See https://en.wikipedia.org/wiki/Fast_inverse_square_root for why this works
When you DO document Python code, most of it should be in docstrings. Every module, most functions or methods, and most classes should have a docstring briefly describing their purpose. When necessary, a docstring can ALSO contain a more in-depth description. Note that this longer description should always be IN ADDITION to the summary, and should still avoid re-describing the code.
Things that are usually NOT necessary in docstrings:
- The name of the function, method, object, or module
- Type information, unless used to generate external documentation
Good things to consider including in docstrings:
- What exceptions the code might throw and when
- Mutually-exclusive arguments
See PEP257 for implementation details.