Objectives: LO-14.1, LO-14.2, LO-14.3, LO-14.4
Prerequisites: the Module 14 reading and
Lab 12
Time: about 2 hours
In this lab you predict what a class’s instances hold, write a class with methods, write a
thermostat that keeps its invariant whatever its callers do, give a class a readable __repr__
and an __eq__, rebuild it as a frozen dataclass, and add type hints. Each exercise ends with a
check cell that prints passed or says what is wrong.
Setup¶
Run the next cell first. It imports what the checks need and seeds random, which the
thermostat’s check uses to try many calls in a repeatable order.
import dataclasses
import math
import random
import sys
import typing
from dataclasses import dataclass
print("Python", sys.version.split()[0])
random.seed(14)1. Instances and methods¶
Read this class and the lines after it, but don’t run anything yet.
class Tally:
def __init__(self, label):
self.label = label
self.marks = []
def mark(self, value):
self.marks.append(value)
return len(self.marks)
rain = Tally("rain")
wind = Tally("wind")
rain.mark(2.4)
n = rain.mark(0.0)
wind.mark(7)
m = Tally.mark(wind, 3)Exercise L14.1 (LO-14.1, ★, about 10 minutes)¶
Predict:
p1: the value ofn.p2: the value ofm.Tally.mark(wind, 3)calls the method through the class, passing the instance yourself.p3:len(rain.marks), after all the lines have run.p4:rain.marks is wind.marks,TrueorFalse.
p1 = 0
p2 = 0
p3 = 0
p4 = NoneNow run the class and check your predictions.
class Tally:
def __init__(self, label):
self.label = label
self.marks = []
def mark(self, value):
self.marks.append(value)
return len(self.marks)
rain = Tally("rain")
wind = Tally("wind")
rain.mark(2.4)
n = rain.mark(0.0)
wind.mark(7)
m = Tally.mark(wind, 3)
print(n, m, len(rain.marks), rain.marks is wind.marks)assert p1 == 2, "p1: the second call to rain.mark makes rain.marks two items long."
assert p2 == 2, "p2: Tally.mark(wind, 3) is wind.mark(3), wind's second mark."
assert p3 == 2, "p3: wind's marks went into wind's own list, not rain's."
assert p4 is False, "p4: __init__ makes a new list for each instance."
print("passed")2. A class of your own¶
Exercise L14.2 (LO-14.1, ★★, about 20 minutes)¶
Write a class Station for a weather station:
Station("Harbor")creates a station with the attributenameand no temperatures yet.add(temp)records one temperature, and returns nothing.count()returns how many temperatures it has recorded.mean()returns their mean, and raisesValueErrorwith a message that says there are no temperatures when there are none.extremes()returns a tuple of the lowest and the highest temperature, and raisesValueErrorthe same way when there are none.
class Station:
"""A weather station and the temperatures it has recorded."""
# Write __init__ and the four methods here.harbor = Station("Harbor")
hilltop = Station("Hilltop")
assert harbor.name == "Harbor", "Station('Harbor').name should be 'Harbor'."
assert harbor.count() == 0, "A new station has recorded nothing."
for method in ["mean", "extremes"]:
try:
getattr(harbor, method)()
except ValueError:
pass
else:
raise AssertionError(f"{method}() should raise ValueError when there are no temperatures.")
for temp in [8.5, 11.0, 6.5]:
assert harbor.add(temp) is None, "add should record the temperature and return nothing."
hilltop.add(-2.0)
assert harbor.count() == 3 and hilltop.count() == 1, (
"Each station needs its own list: make it in __init__, on self."
)
assert math.isclose(harbor.mean(), 26 / 3), f"mean() of 8.5, 11.0, 6.5 gave {harbor.mean()}."
assert harbor.extremes() == (6.5, 11.0), f"extremes() gave {harbor.extremes()}, not (6.5, 11.0)."
assert hilltop.extremes() == (-2.0, -2.0), "With one temperature, it is both lowest and highest."
print("passed")3. Keeping an invariant¶
A thermostat has a target temperature that people change with buttons. The heating system can
work only with targets from 10 to 30 °C, so every Thermostat must keep this invariant:
10 <= target <= 30, at every moment that other code can see it.
Exercise L14.3 (LO-14.2, ★★, about 25 minutes)¶
Write Thermostat, with its invariant in the class’s docstring:
Thermostat()starts with a target of 20.0, andThermostat(18.5)with 18.5.set_target(value)sets a new target.warmer(step=0.5)raises the target bystep, andcooler(step=0.5)lowers it bystep. Each returns the new target.
A target out of range, nan included, and a step that isn’t more than 0, raise ValueError
with a message that says what was wrong, and leave the target as it was. So warmer() at 30
raises instead of going above 30.
The check below calls your thermostat’s methods 2,000 times with random arguments, some of them bad, and checks the invariant after every call.
class Thermostat:
"""Write the docstring, with the invariant."""
# Write __init__, set_target, warmer, and cooler here.assert "10" in (Thermostat.__doc__ or "") and "30" in Thermostat.__doc__, (
"State the invariant in the class's docstring."
)
assert Thermostat().target == 20.0 and Thermostat(18.5).target == 18.5, (
"Thermostat() should start at 20.0, and Thermostat(18.5) at 18.5."
)
for bad in [9.9, 30.5, math.nan, -math.inf]:
try:
Thermostat(bad)
except ValueError:
pass
else:
raise AssertionError(f"Thermostat({bad}) should raise ValueError.")
thermostat = Thermostat()
assert thermostat.warmer() == 20.5 and thermostat.cooler(2) == 18.5, (
"warmer() should add 0.5 and return the target; cooler(2) should take 2 off."
)
calls = []
for number in range(2000):
method = random.choice(["set_target", "warmer", "cooler"])
if method == "set_target":
argument = random.choice([random.uniform(5, 35), 10, 30, math.nan])
else:
argument = random.choice([0.5, 1, 2.5, 0, -1, math.nan])
before = thermostat.target
calls.append(f"{method}({argument})")
try:
getattr(thermostat, method)(argument)
except ValueError:
assert thermostat.target == before, (
f"After {calls[-1]} raised ValueError, the target changed from {before} to "
f"{thermostat.target}. Check before you change anything."
)
assert 10 <= thermostat.target <= 30, (
f"After these calls, the target is {thermostat.target}: {calls[-5:]}"
)
print("passed")4. Printing and comparing¶
Exercise L14.4 (LO-14.3, ★, about 15 minutes)¶
Wind holds a wind speed and the direction it blows from. Add two methods to it:
__repr__, so thatWind(12.0, "NW")shows asWind(speed_kmh=12.0, direction='NW').__eq__, so that twoWindobjects are equal when both their speeds and their directions are equal. For anything that isn’t aWind, returnNotImplemented.
class Wind:
"""A wind speed, in kilometers per hour, and the direction the wind blows from."""
def __init__(self, speed_kmh, direction):
self.speed_kmh = speed_kmh
self.direction = direction
# Write __repr__ and __eq__ here.assert repr(Wind(12.0, "NW")) == "Wind(speed_kmh=12.0, direction='NW')", (
f"repr gave {Wind(12.0, 'NW')!r}. Use !r for each value, so the direction gets its quotes."
)
assert str(Wind(5, "S")) == "Wind(speed_kmh=5, direction='S')", "print should use __repr__ too."
assert Wind(12.0, "NW") == Wind(12.0, "NW"), "Two winds with equal values should be equal."
assert Wind(12.0, "NW") != Wind(12.0, "N"), "Winds from different directions aren't equal."
assert Wind(12.0, "NW") != Wind(15.0, "NW"), "Winds of different speeds aren't equal."
assert Wind(12.0, "NW").__eq__("NW") is NotImplemented, (
"For anything that isn't a Wind, __eq__ should return NotImplemented."
)
assert (Wind(12.0, "NW") == 12.0) is False, "A Wind isn't equal to a number."
print("passed")5. The same class as a dataclass¶
Exercise L14.5 (LO-14.2, LO-14.3, ★★, about 20 minutes)¶
Write WindReading as a frozen dataclass with three fields, each with a type hint, in this
order: station, a string; speed_kmh, a float; and direction_deg, an int, the direction the
wind blows from in degrees, where 0 is north and 90 is east. Give it a __post_init__ that
raises ValueError unless the speed is from 0 to 500 and the direction from 0 to 359. Don’t
write __init__, __repr__, or __eq__: the dataclass writes them.
# Write WindReading here.assert dataclasses.is_dataclass(WindReading), "Mark WindReading with @dataclass."
assert [field.name for field in dataclasses.fields(WindReading)] == [
"station", "speed_kmh", "direction_deg"
], "Give WindReading the fields station, speed_kmh, and direction_deg, in that order."
assert typing.get_type_hints(WindReading) == {
"station": str, "speed_kmh": float, "direction_deg": int
}, f"The fields' type hints are {typing.get_type_hints(WindReading)}."
gale = WindReading("Hilltop", 75.0, 270)
assert repr(gale) == "WindReading(station='Hilltop', speed_kmh=75.0, direction_deg=270)", repr(gale)
assert gale == WindReading("Hilltop", 75.0, 270), "Equal fields should make equal readings."
try:
gale.speed_kmh = 10.0
except dataclasses.FrozenInstanceError:
pass
else:
raise AssertionError("Assigning to a field should fail: use @dataclass(frozen=True).")
assert len({gale, WindReading("Hilltop", 75.0, 270)}) == 1, "Frozen readings can go in a set."
for station, speed, direction in [("A", -1.0, 0), ("A", 500.5, 0), ("A", math.nan, 0),
("A", 10.0, 360), ("A", 10.0, -1)]:
try:
WindReading(station, speed, direction)
except ValueError:
pass
else:
raise AssertionError(f"WindReading({station!r}, {speed}, {direction}) should raise.")
assert WindReading("A", 0.0, 0) and WindReading("A", 500.0, 359), "The ends of each range are good."
print("passed")6. Type hints¶
Exercise L14.6 (LO-14.4, ★★, about 20 minutes)¶
Add type hints to the parameters and return values of these three functions, and to the
variable groups in by_station: a type checker can’t tell from {} alone what an empty
dictionary will hold. Change nothing else.
gust_factordivides two speeds, which may be floats.strongestreturns the reading with the highest speed, orNonefor an empty list.by_stationreturns a dictionary from each station’s name to a list of its readings.
def gust_factor(gust_kmh, mean_kmh):
"""Return how many times stronger the gust is than the mean wind."""
return gust_kmh / mean_kmh
def strongest(readings):
"""Return the reading with the highest speed, or None if there are no readings."""
if not readings:
return None
return max(readings, key=lambda reading: reading.speed_kmh)
def by_station(readings):
"""Return the readings grouped by station, in their order."""
groups = {}
for reading in readings:
groups.setdefault(reading.station, []).append(reading)
return groupsexpected = {
gust_factor: {"gust_kmh": float, "mean_kmh": float, "return": float},
strongest: {"readings": list[WindReading], "return": WindReading | None},
by_station: {"readings": list[WindReading], "return": dict[str, list[WindReading]]},
}
for function, hints in expected.items():
found = typing.get_type_hints(function)
assert found == hints, f"{function.__name__}'s hints are {found}, not {hints}."
print("passed")Now predict what happens when each line below runs, before you run the next cell. For each,
answer "runs" if Python runs it to the end, or "error" if it raises an exception.
gust_factor(40, 20) # h1
gust_factor("40", 20) # h2
strongest(["calm", "breezy"]) # h3Then answer h4: which of the three calls would mypy report, as a list of "h1", "h2", and
"h3"?
h1 = "..."
h2 = "..."
h3 = "..."
h4 = []for name, line in [("h1", 'gust_factor(40, 20)'), ("h2", 'gust_factor("40", 20)'),
("h3", 'strongest(["calm", "breezy"])')]:
try:
eval(line)
print(f"{name}: {line} runs")
except Exception as error:
print(f"{name}: {line} raises {type(error).__name__}: {error}")
assert h1 == "runs", "h1: an int is fine where a float is expected, at run time and for mypy."
assert h2 == "error", "h2: '40' / 20 raises TypeError when the division runs."
assert h3 == "error", "h3: max asks each string for .speed_kmh, which a string doesn't have."
assert sorted(h4) == ["h2", "h3"], (
"h4: mypy reports both calls whose argument doesn't match the hint, before anything runs."
)
print("passed")Summary¶
A class bundles data, in attributes on
self, with the methods that use and change it. Each instance has its own attributes, as long as__init__creates them.An invariant is kept by checking every argument in
__init__and in every method that changes the object, before changing anything. The thermostat’s check tried 2,000 calls and found the invariant true after each one.__repr__and__eq__make objects readable and comparable, and a frozen dataclass writes both, with__init__and a hash, from its fields.Python doesn’t check type hints:
h2andh3ran until an operation failed, inside the function. A type checker reports both calls before the program runs, which Module 18 sets up.