Names, Units, and Readable Code
Python Style and Documentation Conventions
BOTIE
Their purpose was understandable code and consistent expectations. A descriptive name carries information into every use of a value. A docstring records behavior that a name cannot reasonably contain, such as units, an empty-input policy or an exception. The conventions still require judgment about the particular program.
Sources for this history
Which Temperature Does This Program Return?
Botie receives a report with fields called house and temperature_c. One helper returns a field called value. The arithmetic may be right, but the next program cannot tell whether value contains Celsius, Fahrenheit or a temperature difference.
We already know how to write the conversion. Now we need to make its meaning visible in the code. A reader should be able to find the input unit, the rule being applied and the meaning of the returned result without reconstructing them from a few unexplained numbers.
These supplied readings are valid Celsius measurements. A field name explains the intended unit; it cannot establish whether a real thermometer used that unit.
Step 1 of 1
Keep the unit attached to the result
The greenhouse name stays with its temperature throughout the conversion.
| House | Input field: temperature_c | Output field: temperature_f |
|---|---|---|
| north | 0 | 32 |
| south | 20 | 68 |
north
- Input field: temperature_c
- 0
- Output field: temperature_f
- 32
south
- Input field: temperature_c
- 20
- Output field: temperature_f
- 68
Name the quantity and its unit
The converted value keeps its greenhouse name. temperature_f tells the next reader that the number is in Fahrenheit.
Keep Names and Units in the Temperature Report
The north greenhouse reads 0 degrees Celsius and the south reads 20. Their Fahrenheit readings are 32 and 68. The report also needs to say which greenhouse each value belongs to and which unit it uses.
BOTIE
Named Fahrenheit readings
- house
- north
- temperature_f
- 32
- house
- south
- temperature_f
- 68
| house | temperature_f |
|---|---|
| north | 32 |
| south | 68 |
Follow the operations
1. Greenhouse temperatures in Celsius
- house
- north
- temperature_c
- 0
- house
- south
- temperature_c
- 20
house temperature_c north 0 south 20 2. Read greenhouse names
- 0north
- 1south
3. Read temperatures in Celsius
- 00
- 120
4. Celsius-to-Fahrenheit multiplier
1.8
5. Multiply
- 00
- 136
6. Fahrenheit offset
32
7. Add
- 032
- 168
8. Attach names to Fahrenheit readings
- house
- north
- temperature_f
- 32
- house
- south
- temperature_f
- 68
house temperature_f north 32 south 68 9. Result
- house
- north
- temperature_f
- 32
- house
- south
- temperature_f
- 68
house temperature_f north 32 south 68
These supplied readings are valid Celsius measurements. A field name explains the intended unit; it cannot establish whether a real thermometer used that unit.
1. Name the quantity and its unit
A name such as temperature_c tells us more than x. It identifies a temperature and the Celsius convention used by the program. Use names that distinguish a single reading from a collection, and a measured value from its position in a list.
Names still need context. A variable called temperature_c can contain Fahrenheit if the caller supplied the wrong data. State the boundary agreement and check it where the program has enough information to do so.
Long names are useful when they remove ambiguity. Repeating every fact in every local variable can make a short calculation harder to read.
Return a value with an explicit unit
Give the conversion a name that states its direction.
def celsius_to_fahrenheit(temperature_c):
return temperature_c * 1.8 + 32
temperature_f = celsius_to_fahrenheit(10)
print(temperature_f)50.0The function and result name agree about the output unit. The number alone would not communicate it.
2. Document behavior a name cannot explain
A docstring is the string at the start of a function body. Python makes it available through help and the function's __doc__ attribute. Explain the useful agreement: accepted inputs, returned meaning and failure behavior.
A comment has a different job. It can explain a decision that would otherwise be surprising. Restating an obvious assignment adds reading without explaining the decision.
Keep documentation beside the function and revise it when the agreement changes.
Explain why equality counts
The greenhouse safety rule includes a reading exactly at the limit. That policy belongs in the function agreement.
def needs_inspection(temperature_c, limit_c):
"""Return whether a Celsius reading reaches the inclusive limit."""
return temperature_c >= limit_c
print(needs_inspection(25, 25))
print(needs_inspection.__doc__)True
Return whether a Celsius reading reaches the inclusive limit.The docstring states the boundary rule instead of merely saying that the function compares two values.
Check yourself
Questions on Parts 1 to 2
Question 1 of 2
Which output name states the convention?
Question data
Input field temperature_c contains 20. The conversion returns Fahrenheit.3. Let the layout show the steps
Separate a calculation when the intermediate value has a useful meaning. A named list of departures can make an alert calculation easier to inspect than one compressed expression.
PEP 8 gives conventions such as snake_case function names and consistent indentation. A formatter can apply layout rules, but it cannot decide whether a variable describes the right quantity. Read the result as a procedure someone else must follow.
Shorter source is useful only when the operations and their order remain clear.
Keep the calculation and its display separate
The conversion produces data. Formatting produces text for a person.
temperature_c = 15
temperature_f = temperature_c * 1.8 + 32
message = f"north: {temperature_f:.1f} F"
print(message)north: 59.0 FThe numerical result remains available before the display rounds it.
4. Preserve names while changing the representation
A report needs more than an unnamed list of converted temperatures. Keep the greenhouse identifier beside each result. Build new output dictionaries so another part of the program can still inspect the original measurements.
For an individual Python float, the standard library's math.isfinite checks whether the value is finite. It has a similar purpose to the NumPy finite-value check we used for arrays. Import math to access it. Check that a measurement is a number first, because isfinite is not a parser for arbitrary text.
Python integers can grow beyond the range a float can represent. A conversion to a float can raise OverflowError, and floating-point arithmetic can produce infinity even from finite inputs. The conversion exercises reject a result that cannot be represented as a finite float. Counting or storing an integer does not require converting it to a float first.
Use a dictionary when named fields are sufficient. A later lesson introduces dataclasses for records whose structure and behavior deserve a named Python type.
The challenge extends the conversion into a reusable report operation, with explicit errors and unchanged inputs.
Check an individual numerical value
NaN is a special not-a-number value that a dataset may use for missing readings. Infinity is also outside this finite-reading contract.
import math
print(math.isfinite(12.5))
print(math.isfinite(float("nan")))
print(math.isfinite(float("inf")))True
False
FalseThe returned flags describe finiteness. A separate input-type check still decides whether the value is a measurement the function accepts.
Check yourself
Questions on Parts 1 to 4
Question 1 of 4
What useful fact belongs in the docstring?
Question data
The inspection rule is temperature_c >= limit_c. Equality must trigger inspection.Try it with Botie
Build with Botie
Write and run Python