Code style, docstrings and the README
Be able to write code and documentation that another person can use.
Prerequisites
Intuition
Code is read many more times than it is written — often by you, three months from now, when you have forgotten everything.
Names are the cheapest documentation there is: number_passed beats n2. Function names should be verbs (read_csv, compute_mean).
A docstring explains what and why, not how (that is visible in the code):
def mean(values, ignore_empty=False):
"""The mean of values.
An empty list raises ValueError unless ignore_empty=True (then 0.0).
Used by the report, which must not crash on empty groups.
"""
Comments should explain the unexpected: why does it say + 1e-8 here? Not # increase i by 1.
Code
A README that is enough — five headings:
# Project name
One sentence about what it does and who it is for.
## Installation
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
## Usage
python -m myapp.cli --data data/train.csv --out report.md
## Development
pytest -q # tests
ruff check . # the linter
ruff format . # the formatter
## Limitations
Handles Swedish text only; a maximum of 100 MB of input.
Tools do the rest automatically: ruff format (or black) formats it the same way every time — then diffs stop being about whitespace. ruff check finds unused imports, undefined names and common mistakes. Run both in CI and nobody has to nag about style in code review.
Mastery means
- Writes readable names and docstrings
- Writes a README that is enough to get started
- Uses a formatter and a linter
Sign in to do the exercises and build your mastery up.