How should I document my code? I should use a standardized format for docstrings, but which one?
Sources: - Google's Python documentation standard, which depends on: - reStructuredText markup, which is used by: - Sphinx documentation generator (similar to Doxygen).
Will reference Google standard. This is, however, not a priority, so the code is not guaranteed to follow it.
Most interesting parts (to me):
- 2.3: I didn't know how to use subdirectories before.
- 2.4: I didn't know about
finallyblocks. - 2.7: I didn't know about comprehensions & generator expressions before.
Reference the official Google document, not the copy below (if you're not me.) I slimmed it down to only what's important to me.
Also, reStructuredText has a few less commonly used features that I do use in this codebase, namely:
- LaTeX math blocks
- Variables referenced in one-liners and paragraphs are formatted as inline
literals (e.g.
\`variable```)
from x import yshould only be used for modules, not individual functions or variables.- Except for the modules
typingandcollections.abc.
- Except for the modules
from x import y as zmay only be used if the last point is true, and any of the following is true:- Two modules named
yare to be imported. yconflicts with a top-level name in the current module.yconflicts with a common parameter name in the public API.yis an inconveniently long name.yis too generic in the context of your code.
- Two modules named
- Use
import y as zonly whenzis a standard abbreviation.
- A package is an import that references a separate code file within the same project/repository.
- Packages should be imported by their full name (from the root of the Python project)
- To use directories, use a
.instead of a/, and always remove the.pyfile extensions when using imports.
- Exceptions are to be used carefully, and
assertmay only be used in tests (pytest). - Never use catch-all
except:statements, or catchExceptionorStandardErrorunless:- Re-raising the exception
- Creating an isolation point to make sure exceptions aren't propagated, but instead recorded and suppressed.
- Minimize the amount of code in
try/exceptblocks, to ensure you're catching the error you intended to catch. - Use
finallyblock to execute code whether or not an exception is raised.
- Avoid mutable global state.
- In the rare case it's warranted, declare it in a module or class with an
underscore prepended to its name.
- In a comment or linked doc, explain why mutable global state is necessary.
- Module-level constants are encouraged. (Named with all caps)
- Avoid nested classes, and prefix class members that are only used internally
with an
_.
- Optimize for readability, not conciseness.
- Multiple
forclauses or filter expressions not permitted.