Objectives: LO-15.1, LO-15.2, LO-15.3
Prerequisites: the Module 15 reading and
Lab 14
Time: about 2 hours
In this lab you predict which class’s method runs, write two sensor subclasses, watch a
dictionary subclass break its own rule and rebuild it by composition, and give classes
operators, ordering, length, and iteration. Each exercise ends with a check cell that prints
passed or says what is wrong.
Setup¶
Run the next cell first. It defines Sensor, the base class from the reading.
import functools
import inspect
import math
import sys
print("Python", sys.version.split()[0])
class Sensor:
"""A sensor that records numeric readings.
Invariant: every value in values passed check().
"""
unit = ""
def __init__(self, name):
self.name = name
self.values = []
def check(self, value):
"""Raise an exception if value can't be a reading from this sensor."""
if not isinstance(value, (int, float)):
raise TypeError(f"a reading must be a number, not {value!r}")
def record(self, value):
"""Check value, then record it."""
self.check(value)
self.values.append(value)
def describe(self):
"""Return one line about the sensor."""
return f"{self.name} ({self.unit}): {len(self.values)} recorded"1. Which method runs?¶
Read these classes, but don’t run them yet.
class Alert:
def level(self):
return "info"
def message(self, text):
return f"[{self.level()}] {text}"
class Warning(Alert):
def level(self):
return "warning"
class Storm(Warning):
def message(self, text):
return super().message(text.upper())Exercise L15.1 (LO-15.1, ★, about 10 minutes)¶
Predict, as strings:
m1:Alert().message("wind")m2:Warning().message("wind")m3:Storm().message("wind")
and, as a list of class names, m4: the method resolution order of Storm, from Storm to
object.
m1 = "..."
m2 = "..."
m3 = "..."
m4 = []class Alert:
def level(self):
return "info"
def message(self, text):
return f"[{self.level()}] {text}"
class Warning(Alert):
def level(self):
return "warning"
class Storm(Warning):
def message(self, text):
return super().message(text.upper())
print(Alert().message("wind"), Warning().message("wind"), Storm().message("wind"))
print([cls.__name__ for cls in Storm.__mro__])assert m1 == "[info] wind", "m1: Alert's own level and message."
assert m2 == "[warning] wind", (
"m2: Warning inherits message, but self.level() finds Warning's level first."
)
assert m3 == "[warning] WIND", (
"m3: Storm.message uppercases the text and calls Warning's inherited message, whose "
"self.level() is still found on Warning."
)
assert m4 == ["Storm", "Warning", "Alert", "object"], "m4: from the class up to object."
print("passed")Warning here is a class of this lab’s own, which hides Python’s built-in Warning for the
rest of the notebook; that is harmless here, but in your own code, avoid reusing built-in names.
2. Subclasses¶
Exercise L15.2 (LO-15.1, ★★, about 20 minutes)¶
Write two subclasses of Sensor:
Barometer, withunit = "hPa", whosecheckextendsSensor’s: after the number check, it raisesValueErrorunless the pressure is from 870 to 1085 hPa.RainSensor, withunit = "mm", which takes a second argument,area_cm2, the area of its funnel, and stores it. Itscheckrefuses negative amounts withValueError, and itsdescribeadds, funnel <area_cm2> cm²toSensor’s line, so that a sensor named"Roof"with a 200 cm² funnel and two readings describes itself asRoof (mm): 2 recorded, funnel 200 cm².
Use super() for everything Sensor already does: don’t copy its code.
# Write Barometer and RainSensor here.for cls in ["Barometer", "RainSensor"]:
assert cls in globals() and issubclass(globals()[cls], Sensor), (
f"Define {cls} as a subclass of Sensor."
)
pressure = Barometer("Harbor pressure")
pressure.record(1013.2)
assert pressure.unit == "hPa" and pressure.values == [1013.2], "Barometer should record 1013.2."
for bad, error in [(869.9, ValueError), (1085.1, ValueError), (math.nan, ValueError),
("1013", TypeError)]:
try:
pressure.record(bad)
except error:
pass
else:
raise AssertionError(f"Barometer.record({bad!r}) should raise {error.__name__}.")
assert pressure.values == [1013.2], "A refused reading must not be recorded."
roof = RainSensor("Roof", 200)
roof.record(2.4)
roof.record(0)
assert roof.area_cm2 == 200 and roof.name == "Roof", "RainSensor('Roof', 200) sets both."
assert roof.describe() == "Roof (mm): 2 recorded, funnel 200 cm²", (
f"describe gave {roof.describe()!r}."
)
for bad, error in [(-0.1, ValueError), ("2", TypeError)]:
try:
roof.record(bad)
except error:
pass
else:
raise AssertionError(f"RainSensor.record({bad!r}) should raise {error.__name__}.")
for method in [Barometer.check, RainSensor.__init__, RainSensor.check, RainSensor.describe]:
source = inspect.getsource(method)
assert "super()" in source and "isinstance" not in source, (
f"{method.__qualname__}: call super() instead of copying Sensor's code."
)
print("passed")3. Inheritance that breaks a rule, and composition that keeps it¶
A registry maps each station’s name to its Sensor. Its invariant: every key is the name of the
sensor it maps to. This version inherits from dict and checks the one way it expected keys to
be added. Run it, and watch three other ways in.
class DictRegistry(dict):
"""Sensors by name. Invariant: each key is its sensor's name."""
def __setitem__(self, name, sensor):
if name != sensor.name:
raise ValueError(f"key {name!r} doesn't match the sensor's name {sensor.name!r}")
super().__setitem__(name, sensor)
registry = DictRegistry()
registry["Harbor"] = Sensor("Harbor")
registry.update({"Hilltop": Sensor("Airport")})
registry.setdefault("Riverside", Sensor("Harbor"))
registry |= {"Pier": Sensor("Quay")}
for key, sensor in registry.items():
print(f"{key!r:12} -> {sensor.name!r}")Exercise L15.3 (LO-15.2, ★★, about 25 minutes)¶
Write
Registryby composition: it keeps a dictionary in an attribute,_sensors, and offers only these methods:register(sensor)adds a sensor under its own name, and raisesValueErrorif a sensor with that name is already registered;get(name)returns the sensor with that name, and raisesKeyErrorwith a message that names it if there is none;__len__, the number of sensors;__iter__, which gives the names, in alphabetical order.
Set
whyto the letter of the best reason for choosing composition here:"A": composition is faster than inheritance."B": a registry isn’t a dictionary in every way a dictionary can be used: as a subclass, it inherits every way to add a key, and must check each one."C": Python doesn’t allow subclasses ofdict.
class Registry:
"""Sensors by name. Invariant: each key is its sensor's name, registered once."""
# Write __init__, register, get, __len__, and __iter__ here.
why = "..."sensors = Registry()
for name in ["Riverside", "Harbor", "Airport"]:
sensors.register(Sensor(name))
assert len(sensors) == 3, "len should count the registered sensors."
assert list(sensors) == ["Airport", "Harbor", "Riverside"], (
f"Iterating should give the names in alphabetical order, not {list(sensors)}."
)
assert list(sensors) == list(sensors), "Each loop should start again: return a new iterator."
assert sensors.get("Harbor").name == "Harbor", "get('Harbor') should return Harbor's sensor."
try:
sensors.register(Sensor("Harbor"))
except ValueError:
pass
else:
raise AssertionError("Registering a second sensor named Harbor should raise ValueError.")
try:
sensors.get("Pier")
except KeyError as error:
assert "Pier" in str(error), "The KeyError's message should name the missing sensor."
else:
raise AssertionError("get('Pier') should raise KeyError.")
assert not isinstance(sensors, dict), "Registry should hold a dictionary, not be one."
for method in ["update", "setdefault", "__setitem__", "__ior__"]:
assert not hasattr(sensors, method), f"Registry shouldn't offer {method}."
assert why == "B", "why: inheritance hands over every method of dict, including update and |=."
print("passed")4. Operators¶
Exercise L15.4 (LO-15.3, ★★, about 20 minutes)¶
Finish Vector: add __add__ and __sub__ for two vectors, __mul__ and __rmul__ for a
vector and a number (an int or a float), and __neg__, which -v calls. Each returns a new
Vector and leaves its operands unchanged, and the binary ones return NotImplemented for an
operand they can’t handle.
class Vector:
"""A two-dimensional vector."""
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x!r}, {self.y!r})"
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __abs__(self):
return math.hypot(self.x, self.y)
# Write __add__, __sub__, __mul__, __rmul__, and __neg__ here.a, b = Vector(3, 4), Vector(1, -2)
assert a + b == Vector(4, 2) and a - b == Vector(2, 6), f"a + b gave {a + b}, a - b {a - b}."
assert a * 2 == Vector(6, 8) and 0.5 * a == Vector(1.5, 2.0), "Check __mul__ and __rmul__."
assert -a == Vector(-3, -4), f"-a gave {-a}."
assert a == Vector(3, 4) and b == Vector(1, -2), "The operators must not change their operands."
assert abs(2 * a - a) == 5.0, "abs(2 * a - a) should be 5.0."
for expression in ["a + 1", "a - 'x'", "a * a", "'x' * a"]:
try:
eval(expression)
except TypeError:
pass
else:
raise AssertionError(f"{expression} should raise TypeError: return NotImplemented.")
print("passed")5. Ordering¶
Exercise L15.5 (LO-15.3, ★★, about 15 minutes)¶
TimeOfDay(hour, minute) is a time on a 24-hour clock. Give it __eq__ and __lt__, so that
times sort from midnight on, and decorate the class with @functools.total_ordering, which
writes <=, >, and >= from those two.
class TimeOfDay:
"""A time on a 24-hour clock."""
def __init__(self, hour, minute):
if not (0 <= hour <= 23 and 0 <= minute <= 59):
raise ValueError(f"not a time: {hour}:{minute}")
self.hour = hour
self.minute = minute
def __repr__(self):
return f"TimeOfDay({self.hour}, {self.minute})"
# Write __eq__ and __lt__ here, and add the decorator.times = [TimeOfDay(14, 5), TimeOfDay(9, 30), TimeOfDay(14, 0), TimeOfDay(0, 15)]
assert sorted(times) == [TimeOfDay(0, 15), TimeOfDay(9, 30), TimeOfDay(14, 0), TimeOfDay(14, 5)], (
f"sorted gave {sorted(times)}."
)
assert max(times) == TimeOfDay(14, 5), "max should be the latest time."
try:
ordered = TimeOfDay(9, 30) <= TimeOfDay(9, 30) and TimeOfDay(14, 5) >= TimeOfDay(14, 0)
except TypeError:
ordered = False
assert ordered, "<= and >= should work: decorate the class with @functools.total_ordering."
assert not TimeOfDay(9, 30) < TimeOfDay(9, 30), "A time isn't earlier than itself."
try:
same = TimeOfDay(9, 30) == "9:30"
except AttributeError:
same = None
assert same is False, "Comparing with a string should give False: return NotImplemented for it."
print("passed")6. Length and iteration¶
Exercise L15.6 (LO-15.3, ★★, about 20 minutes)¶
Hours(first, last, step)is an iterator over the hours fromfirsttolast, both included if the steps reachlast, going up bystep.Hours(6, 18, 3)gives 6, 9, 12, 15, and 18. Give it__iter__and__next__.Forecastholds one day’s expected temperatures by hour. Give it__len__, the number of hours it holds, and__iter__, which gives(hour, temp)pairs in order of the hour, and can be looped over any number of times.
class Hours:
"""An iterator over the hours from first to last, going up by step."""
def __init__(self, first, last, step=1):
self.next_hour = first
self.last = last
self.step = step
# Write __iter__ and __next__ here.
class Forecast:
"""Expected temperatures for one day, by hour."""
def __init__(self):
self._temps = {}
def expect(self, hour, temp):
"""Record the temperature expected at an hour."""
self._temps[hour] = temp
# Write __len__ and __iter__ here.forecast = Forecast()
for hour, temp in [(15, 12.5), (9, 7.0), (12, 11.0)]:
forecast.expect(hour, temp)
assert list(Hours(6, 18, 3)) == [6, 9, 12, 15, 18], f"Hours(6, 18, 3) gave {list(Hours(6, 18, 3))}."
assert list(Hours(0, 5, 2)) == [0, 2, 4], "Hours(0, 5, 2) should stop at 4, before passing 5."
assert list(Hours(7, 6)) == [], "Hours(7, 6) gives nothing: 7 is already past 6."
hours = Hours(1, 3)
assert iter(hours) is hours, "An iterator's __iter__ returns the iterator itself."
assert next(hours) == 1 and list(hours) == [2, 3] and list(hours) == [], (
"An iterator keeps its place, and is used up after one pass."
)
assert len(forecast) == 3, f"len(forecast) gave {len(forecast)}."
assert list(forecast) == [(9, 7.0), (12, 11.0), (15, 12.5)], f"Pairs: {list(forecast)}."
assert list(forecast) == list(forecast), "A Forecast should be loopable again and again."
assert max([temp for hour, temp in forecast]) == 12.5, "max over the pairs' temperatures."
print("passed")7. Duck typing¶
Exercise L15.7 (LO-15.3, ★, about 10 minutes)¶
This function knows nothing about the classes in this lab:
def busiest(collections):
"""Return the collection with the most items."""
return max(collections, key=len)For each call, predict "works" or "error". The calls use the classes from exercises L15.3 and
L15.6, so finish those first.
d1:busiest([sensors, [1, 2], "abcd"]), with theRegistryfrom exercise L15.3d2:busiest([forecast, Hours(1, 9)])d3:busiest([Forecast(), {}])
d1 = "..."
d2 = "..."
d3 = "..."def busiest(collections):
"""Return the collection with the most items."""
return max(collections, key=len)
for name, call in [("d1", lambda: busiest([sensors, [1, 2], "abcd"])),
("d2", lambda: busiest([forecast, Hours(1, 9)])),
("d3", lambda: busiest([Forecast(), {}]))]:
try:
print(name, "returns", call())
except TypeError as error:
print(name, "raises TypeError:", error)
assert d1 == "works", "d1: a Registry, a list, and a string all have __len__; 'abcd' wins with 4."
assert d2 == "error", "d2: Hours is an iterator without __len__."
assert d3 == "works", "d3: both have a length, 0; max returns the first."
print("passed")Summary¶
A subclass inherits, overrides, and extends its base class’s methods.
self.method()in a base class runs the subclass’s version, which is howSensor.recordenforced each subclass’scheck.DictRegistrybroke its invariant throughupdate,setdefault, and|=, three methods it inherited and never checked.Registry, by composition, offers only the methods that keep it.Special methods connect a class to Python’s operators, to sorting, to
len, and tofor. An iterable makes a new iterator for each loop; an iterator is used up after one.busiestworked with any object that has a length, whatever its class: duck typing.