Docstrings and Readable Code
A docstring is a short string placed at the top of a function body to explain what the function does.
Docstrings are for readers. They are useful when the function name and parameters are not enough.
Write the Contract
A good beginner docstring says what the function returns:
This is short, but it tells the reader how to check the function.
Prefer Clear Names First
Do not use a docstring to rescue confusing names.
Less clear:
Clearer:
Use the docstring when it adds meaning, not when the names should have done the work.
A Small Milestone
The functions in this chapter can now form a tiny toolkit:
Three small functions
The milestone functions are short enough to test by hand.
Ready to run.
Comments Should Not Repeat the Code
Do not write a paragraph when a sentence is enough. A docstring should help the next reader quickly understand the function.
What value does this function return?
Compute it first, then check your number.
HintSubstitute into the contract
Replace weight, value, and bias in weight * value + bias with the
supplied arguments.
SolutionThe function returns fourteen
The return expression becomes 3 * 4 + 2. Multiplication produces 12, then
adding the bias produces 14.
Readable Code Explains Intent
Readable functions have clear names, visible inputs, a returned value, and a short note when the purpose needs one.