Functions that keep their promises
In 1999 a Mars orbiter was lost because one team's software worked in pound-force seconds and another's expected newton-seconds. What one line of documentation could have helped?
About 35 min · 3 goals · Checked by automated tests
1.Why should I care?
A function's contract is its promise: give me these inputs, in these units, and I will return this. Teams build on each other's contracts every day. Writing them down, and checking them, turns silent wrong answers into loud, early errors.
- ◇ Write a docstring that states a function's inputs, units, output and failure behaviour.
- ◇ Design functions with a single responsibility that return values instead of printing them.
- ◇ Check preconditions and raise a clear error when a contract is broken.
2.Discover
In the Code Lab, write battery_runtime_h with a docstring and a check that both inputs are positive. Call it with good values, then with current_ma = 0 and capacity_mah = -500. Read each error message: does it tell the caller what to fix?
Can't use the interactive? Read a description instead
The Code Lab activity can be done on paper: write the function's docstring with inputs, units, ranges and return value, then list what it should do for capacity 2200 and current 550 (return 4.0), current 0 (raise ValueError) and capacity −500 (raise ValueError).
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
Docstring: 'Returns the distance.' What is the most important thing missing for an engineer using it?
Practice 2
Using battery_runtime_h from the worked example, what does battery_runtime_h(3000, 750) return, in hours?
4.Apply it
Write wheel_rpm(speed_m_s, diameter_m) for a rover: a docstring with units and ranges, checks that raise ValueError for bad inputs, and a returned value. Test it on 0.5 m/s with a 0.12 m wheel (about 79.6 rpm) and on two bad inputs.
5.Understand
A docstring is the contract
State what each parameter means, its units and allowed range, what is returned (with units), and what happens on bad input. Someone should be able to use the function correctly from the docstring alone, without reading the body.
One job, returned not printed
A function that reads a file, converts units, averages and prints is four functions tangled together. Split it so each does one thing and returns its result. Returned values can be tested, reused and fed into the next step; printed text can only be read by a person.
Fail loudly at the boundary
Check preconditions at the top of the function and raise ValueError("...") with a message that names the bad value. An early, specific error is far cheaper than a wrong number discovered three modules later.
Explain it another way
A vending machine has a contract printed on it: insert coins, press a code, get a snack. It rejects foreign coins straight away instead of keeping them and giving you nothing. Good functions behave the same way.
Preconditions are what must be true of the inputs; postconditions are what the function guarantees about its output. Python's convention is to raise ValueError for a value of the right type but wrong range and TypeError for the wrong type. Type hints such as def f(x: float) -> float document types but are not enforced at run time.
Flight software standards require every interface to state units and ranges, because many costly failures have come from two correct pieces of code that disagreed about what a number meant.
Worked example 1
Write a contract-checked runtime function for a robot battery.
def battery_runtime_h(capacity_mah, current_ma):
"""Estimate runtime in hours.
capacity_mah: usable capacity in milliamp-hours, > 0
current_ma: average current draw in milliamps, > 0
Returns the runtime in hours. Raises ValueError for non-positive inputs.
"""
if capacity_mah <= 0:
raise ValueError(f"capacity_mah must be positive, got {capacity_mah}")
if current_ma <= 0:
raise ValueError(f"current_ma must be positive, got {current_ma}")
return capacity_mah / current_ma
print(battery_runtime_h(2200, 550)) # 4.0
try:
battery_runtime_h(2200, 0)
except ValueError as err:
print("Rejected:", err)Common mix-ups
- Error checks make code longer for no reason.
✓ Two lines of checking can save hours of hunting a wrong number back to its source. - Type hints stop wrong inputs.
✓ Python does not enforce them at run time. They document intent; range checks still need code.
6.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
Which function design is best for a sensor-log tool?
Practice 4
wheel_rpm(speed_m_s, diameter_m) is called with diameter_m = -0.1. Which response best keeps the contract?
Practice 5
A function prints the average current instead of returning it. What can't you do?
7.Predict
battery_runtime_h(capacity_mah, current_ma) returns capacity / current. Someone calls it with current_ma = 0. What should a well-designed version do?
Guess first. Being wrong here is how the surprise works.
8.Reflect
9.Go further
- Python tutorial: Errors and exceptions ↗How raise, try and except work, with the built-in exception types.
Concepts: Functions and decomposition · Testing and debugging