本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
20Modules, Interfaces and Libraries
Twenty programs of the town hall use the same small module of dates: the school calendar, the library’s loans, the market’s opening days. One summer the module is rewritten and becomes thousands of times faster on large calendars. None of the twenty programs is changed, none of them breaks, and their authors only notice that things run faster.
That is possible because the twenty programs relied only on what the module promised, never on how it kept its dates. This chapter splits programs into modules, separates the promise from the way it is kept, reads the documentation of Python’s own modules, and then changes an implementation behind its users’ backs, with the tests to prove nothing broke.
You already know
A function has parameters and returns a value (the first book of the series). A specification states what a function must do, and tests check it (chapter 1); a set answers x in s without a scan (chapter 2); the number of halvings and the cost of searching (chapter 17).
20.1 Splitting a program into modules
Definition 20.1 (Module)
A module is a file of code whose names, functions, constants and others, other programs can use by importing it. In Python every file name.py is a module named name.
"""Points of the plane as pairs (x, y): distances and perimeters."""
import math
def _square(v):
return v * v
def distance(p, q):
"""Return the distance between the points p and q."""
return math.sqrt(_square(p[0] - q[0]) + _square(p[1] - q[1]))
def perimeter(points):
"""Return the length of the closed path through points, in order.
points is a list of at least two pairs (x, y); the path goes back
from the last point to the first.
"""
total = 0.0
for i in range(len(points)):
total += distance(points[i], points[(i + 1) % len(points)])
return total
import geometry runs the file once and makes the single name geometry available; its contents are reached through it, as geometry.distance. from geometry import perimeter copies one name into the program, to be used without the prefix.
import geometry
from geometry import perimeter
square = [(0, 0), (3, 0), (3, 3), (0, 3)]
print(geometry.distance((0, 0), (3, 4)))
print(perimeter(square))
print("module:", geometry.__name__, "| this program:", __name__)
print("names in geometry:", [n for n in dir(geometry) if not n.startswith("__")])
$ python use_geometry.py
5.0
12.0
module: geometry | this program: __main__
names in geometry: ['_square', 'distance', 'math', 'perimeter']
math, which it imported for itself, and the helper _square.Python looks for a module first in the directory of the program being run, then in the directories listed in the variable PYTHONPATH, then where the installation keeps its modules; the list is in sys.path. A module named like one of Python’s own, random.py next to a program, hides the real one: a classic trap.
Each module has a name in the variable __name__. A file started as a program gets the name "__main__"; imported, it gets its own name. The guard if __name__ == "__main__": keeps a demonstration from running when the file is only imported.
"""Greets only when started as a program, not when imported."""
def greet(name):
return f"hello, {name}"
print("main_guard is running as", __name__)
if __name__ == "__main__":
print(greet("ada"))
$ python main_guard.py
main_guard is running as __main__
hello, ada
$ python import_guard.py
main_guard is running as main_guard
hello, Brenmoor
import_guard.py, which calls greet itself: the module’s own greeting does not run.A module’s statements run only at its first import; a second import in the same run finds it already loaded.
20.2 The interface and the hidden implementation
Definition 20.2 (Interface, implementation)
The interface of a module is what its users may rely on: the names it offers and, for each, a specification. The implementation is the code that keeps these promises, and everything else in the module: helpers, data structures, imported modules.
Python does not lock anything away: geometry._square can be called. The protection is a convention: a name beginning with an underscore is internal, and from geometry import * does not even copy it. A name that is not documented, or that the module only imported for itself, as geometry.math, is internal too.
The documentation of a function is its docstring, which help prints.
import geometry
help(geometry.perimeter)
$ python help_view.py
Help on function perimeter in module geometry:
perimeter(points)
Return the length of the closed path through points, in order.
points is a list of at least two pairs (x, y); the path goes back
from the last point to the first.
20.3 The standard library and its documentation
Definition 20.3 (Library, standard library)
A library is a collection of modules written to be used by other programs. The standard library of a language is the library that comes with every installation of it.
Definition 20.4 (API)
The API, for application programming interface, of a library is its interface: the names, with their specifications, that programs may use.
Python’s standard library has hundreds of modules, and its documentation describes each function in a fixed shape: the signature, what it returns, what it raises and when, examples, and in which version it changed.
statistics.median, shortened. Reading the raised exceptions and the examples is part of reading the entry.import random
import statistics
from collections import Counter
from datetime import date, timedelta
rng = random.Random(7)
print(rng.choice(["letter", "packet", "parcel"]))
print(statistics.median([3, 1, 4, 1, 5, 9]), statistics.median([3, 1, 4]))
print(Counter("abracadabra").most_common(3))
d = date.fromisoformat("2026-11-20")
print(d, d.weekday(), d + timedelta(days=100), date(2027, 1, 1) - d)
$ python stdlib_tour.py
packet
3.5 3
[('a', 5), ('b', 2), ('r', 2)]
2026-11-20 4 2027-02-28 42 days, 0:00:00
Each line of the output is explained by an entry:
random.choicereturns an element of a non-empty sequence, and raisesIndexErroron an empty one. The documentation also warns that, for a given seed, onlyrandom()itself is guaranteed to give the same numbers in every version of Python;choicemay change.statistics.medianof an even number of values is the mean of the two middle ones, here .Counter.most_commonlists equal counts in the order first met:bbeforer.date.weekday()numbers Monday to Sunday : is a Friday. Subtracting two dates gives atimedelta, here days; years run from to .
Remark 20.5
The documentation is written for one version of Python. The entries of this book were read for version ; an entry that says “changed in version” or “new in version” tells what an older or newer Python does differently.
20.4 Changing an implementation without touching its users
The module of dates of the town hall, met at the start of the chapter, offers five functions. Its first implementation keeps the dates in a list.
"""A set of dates, kept in a list.
Interface: empty(), from_dates(dates), add(s, d), contains(s, d), size(s).
"""
def empty():
"""Return a new set of dates, with no date in it."""
return []
def from_dates(dates):
"""Return a new set holding the dates of the iterable dates."""
return list(dict.fromkeys(dates))
def add(s, d):
"""Add the date d to s; nothing changes if d is already in s."""
if d not in s:
s.append(d)
def contains(s, d):
"""Return True when the date d is in s."""
return d in s
def size(s):
"""Return the number of dates in s."""
return len(s)
The second keeps them in a Python set; only the bodies change, and they become shorter.
def empty():
"""Return a new set of dates, with no date in it."""
return set()
def from_dates(dates):
"""Return a new set holding the dates of the iterable dates."""
return set(dates)
def add(s, d):
"""Add the date d to s; nothing changes if d is already in s."""
s.add(d)
def contains(s, d):
"""Return True when the date d is in s."""
return d in s
def size(s):
"""Return the number of dates in s."""
return len(s)
from datetime import date
import dateset_list
import dateset_set
for ds in [dateset_list, dateset_set]:
holidays = ds.empty()
for text in ["2026-01-01", "2026-05-01", "2026-12-25", "2026-05-01"]:
ds.add(holidays, date.fromisoformat(text))
print(ds.__name__, "size", ds.size(holidays),
"| 25 December:", ds.contains(holidays, date(2026, 12, 25)),
"| 24 December:", ds.contains(holidays, date(2026, 12, 24)))
$ python use_dateset.py
dateset_list size 3 | 25 December: True | 24 December: False
dateset_set size 3 | 25 December: True | 24 December: False
The tests are written against the interface only, and the same file tests every implementation, named on the command line.
"""The tests of the interface: python dateset_tests.py list|set|sorted."""
import importlib
import sys
import unittest
from datetime import date
name = sys.argv.pop(1) if len(sys.argv) > 1 else "list"
ds = importlib.import_module("dateset_" + name)
NEW_YEAR, LABOUR_DAY = date(2026, 1, 1), date(2026, 5, 1)
class DatesetTests(unittest.TestCase):
def test_empty(self):
s = ds.empty()
self.assertEqual(ds.size(s), 0)
self.assertFalse(ds.contains(s, NEW_YEAR))
def test_add_twice(self):
s = ds.empty()
ds.add(s, NEW_YEAR)
ds.add(s, NEW_YEAR)
self.assertEqual(ds.size(s), 1)
def test_contains(self):
s = ds.from_dates([LABOUR_DAY, NEW_YEAR, LABOUR_DAY])
self.assertTrue(ds.contains(s, NEW_YEAR))
self.assertFalse(ds.contains(s, date(2026, 1, 2)))
self.assertEqual(ds.size(s), 2)
if __name__ == "__main__":
print("implementation:", ds.__name__, flush=True)
unittest.main(verbosity=2)
$ python dateset_tests.py list 2>&1 | grep -v '^Ran '
implementation: dateset_list
test_add_twice (__main__.DatesetTests.test_add_twice) ... ok
test_contains (__main__.DatesetTests.test_contains) ... ok
test_empty (__main__.DatesetTests.test_empty) ... ok
----------------------------------------------------------------------
OK
$ python dateset_tests.py set 2>&1 | grep -v '^Ran '
implementation: dateset_set
test_add_twice (__main__.DatesetTests.test_add_twice) ... ok
test_contains (__main__.DatesetTests.test_contains) ... ok
test_empty (__main__.DatesetTests.test_empty) ... ok
----------------------------------------------------------------------
OK
Method 20.6 (Changing an implementation safely)
- Write the interface down: the names and the specification of each, in docstrings.
- Write tests that use the interface only, and check that they pass on the old implementation.
- Write the new implementation with the same names and specifications.
- Run the same tests on it. Users need change nothing but, at most, the name of the module they import.
20.5 Libraries outside the standard library, and what languages share
In practice — Libraries from elsewhere
Thousands of libraries are published outside the standard library. Python’s installer, pip, fetches them from a public index; other languages have their own installers. Before relying on one, a programmer checks its version (an update may change the interface), its licence (what it allows), and whether it is still maintained. This book installs nothing: every program in it uses the standard library only.
Languages differ in their spelling, much less in their constructions. The same few constructions appear in the toy machine’s assembly language of chapter 13 and in Python:
| construction | toy assembly | Python |
|---|---|---|
| assignment | LOADI R0, 3 | r0 = 3 |
| sequence | one instruction after another | one line after another |
| conditional | CMP then JC to a label | if a < b: |
| loop | JNZ loop back to a label | while r0 != 0: |
| call | CALL square, RET | square(x), return |
A compiler or an interpreter translates the right-hand column into something like the middle one.
20.6 Exercises
Exercise 20.1 ★
After import geometry alone, which of these work: geometry.distance((0, 0), (1, 1)), distance((0, 0), (1, 1)), geometry.math.sqrt(4)? Which should a user avoid, even if it works?
Solution
Solution of Exercise 20.1.
geometry.distance((0, 0), (1, 1)) works and returns . distance(...) raises NameError: import geometry makes only the name geometry available. geometry.math.sqrt(4) works and returns 2.0, but math is a module that geometry imported for itself, an implementation detail: a user imports math directly.
Exercise 20.2 ★
The file report.py holds the line print(__name__). The file main.py holds import report then print(__name__). What does python main.py print? And python report.py?
Solution
Solution of Exercise 20.2.
Running main.py prints report, when the import runs report.py, and then __main__. Running report.py as a program prints __main__.
Exercise 20.3 ★
A module defines MAX_SIZE, _cache, load, _parse and save, and imports json. Which names belong to its interface?
Exercise 20.4 ★
From the entries quoted in the chapter, give without running them statistics.median([7, 1, 3, 9]) and Counter("banana").most_common(2).
Solution
Solution of Exercise 20.4.
Sorted, the values are ; an even count gives the mean of the two middle ones: 5.0. [('a', 3), ('n', 2)]: three a, two n, one b.
Exercise 20.5 ★
Write a module temperature with two functions, to_fahrenheit(c) and to_celsius(f), each with a docstring. (Fahrenheit is Celsius times , plus .)
Solution
Solution of Exercise 20.5.
In temperature.py:
def to_fahrenheit(c):
"""Return the temperature c, in degrees Celsius, in degrees Fahrenheit."""
return c * 9 / 5 + 32
def to_celsius(f):
"""Return the temperature f, in degrees Fahrenheit, in degrees Celsius."""
return (f - 32) * 5 / 9
The tests check against and that is the same on both scales.
Exercise 20.6 ★★
stops.py starts with import lines, defines FIRST_STOP = "Market Square", then prints lines.LINES[0]; lines.py starts with import stops and defines LINES from stops.FIRST_STOP. python stops.py stops with AttributeError: partially initialized module 'lines' has no attribute 'LINES'. Explain, and correct.
Solution
Solution of Exercise 20.6.
python stops.py runs stops.py as __main__. Its first line starts loading lines, whose first line imports stops: a second module, made from the same file. That one imports lines, which is already being loaded and is returned as it is, without LINES yet; it then defines FIRST_STOP and reads lines.LINES: the error. Two modules that each need the other at import time form a cycle. Correction: put FIRST_STOP in a third module, places.py, which both import, and which imports neither.
Exercise 20.7 ★★
A program does holidays = dateset_list.from_dates(days), then holidays.sort() and prints holidays[0], the earliest holiday. It breaks when the town switches to dateset_set. Whose fault is it, and how should the earliest date be obtained?
Solution
Solution of Exercise 20.7.
The user’s: the interface never promised a list, and sort and [0] rely on the implementation. The set has no sort and no index. The right way is to ask the module’s author for a function in the interface, such as earliest(s), implemented by each version (min(s) for the list and the set, s[0] for the sorted list).
Exercise 20.8 ★★
Rewrite geometry.perimeter without indices, with zip, so that the same tests still pass.
Solution
Solution of Exercise 20.8.
def perimeter(points):
pairs = zip(points, points[1:] + points[:1])
return sum(distance(p, q) for p, q in pairs)
points[1:] + points[:1] is the list shifted by one place, the first point moved to the end: zip pairs each point with the next, and the last with the first. The tests compare it with the original on random polygons.
Exercise 20.9 ★★
For dates, how many dates do add and contains look at, at most, in dateset_list? What about dateset_set?
Solution
Solution of Exercise 20.9.
In dateset_list, contains compares with up to dates, and add too, since it first checks that the date is absent. In dateset_set, both compute where the date is stored, and look at about one date, whatever (chapter 17).
Exercise 20.10 ★★
What does this print, and why? print(pow(2, 10)), then from math import *, then again print(pow(2, 10)).
Solution
Solution of Exercise 20.10.
1024, then 1024.0. from math import * copies all of math’s public names, among them math.pow, which replaces the built-in pow; math.pow converts its arguments to float. The import changed the meaning of a name the program already used.
Exercise 20.11 ★★
After reading the entry for Counter, write word_count(text, n), which returns the n most common words of a text in lower case, with their counts, punctuation removed.
Solution
Solution of Exercise 20.11.
def word_count(text, n):
words = [w.strip(".,;:!?") for w in text.lower().split()]
return Counter(w for w in words if w).most_common(n)
On "The cat saw the dog. The dog saw the cat run." with : [('the', 4), ('cat', 2), ('saw', 2)]; cat comes before saw and dog, met first.
Exercise 20.12 ★★★
Design, in prose, the interface of a module of queues, the waiting line where the first in is the first out: the names of the functions and the specification of each, including what happens on an empty queue.
Solution
Solution of Exercise 20.12.
One possible interface:
new_queue(): returns a new empty queue;push(q, x): addsxat the end ofq;pop(q): removes and returns the element at the front, the earliest pushed of those still there; on an empty queue it raisesIndexErrorand leaves the queue unchanged;is_empty(q): returnsTruewhenqholds no element;size(q): returns the number of elements ofq.
Nothing says how the elements are kept: a list, or two lists, could implement it, and a later chapter does.
Exercise 20.13 ★★★
Write a module dates_chosen that offers the five names of the interface, taken from dateset_list when the environment variable DATESET is list, and from dateset_set otherwise. How can a single test file check both?
Solution
Solution of Exercise 20.13.
import os
if os.environ.get("DATESET", "set") == "list":
from dateset_list import add, contains, empty, from_dates, size
else:
from dateset_set import add, contains, empty, from_dates, size
The choice is made once, at the first import. A test file can run the same tests twice, in two separate runs, DATESET=list python tests.py and DATESET=set python tests.py; or, within one run, set the variable, remove dates_chosen from sys.modules so that it is imported again, and import it again. (The chapter’s dateset_tests.py makes the choice differently, from the command line.)
Exercise 20.14 ★★★
Twenty programs call contains in about ten places each. Compare how many lines of user code change when the implementation changes from list to set, and when the interface renames contains to has.
Solution
Solution of Exercise 20.14.
Implementation changed, interface kept: no line of the twenty programs changes, or at most the import line of each, lines, if the module’s name changes. Interface changed: each of the calls is rewritten, in programs written by others, and any missed one fails only when it runs. A change behind the interface costs the module’s author alone; a change of the interface costs every user.
Exercise 20.15 ★★★
The module primes computes, at its top level, all the primes below a million, and prints computing the primes below 1000000.... Every program that imports it, even to read a constant, prints the message and waits. Correct the module so that the work is done only when a prime is first asked for.
Solution
Solution of Exercise 20.15.
LIMIT = 1_000_000
_sieve = None
def is_prime(n):
if _sieve is None:
_build()
return _sieve[n]
_build holds the sieve of the old top level, assigning the global _sieve; the message is gone. Importing now only defines names; the first call to is_prime pays for the sieve, once. The tests check that importing prints nothing and that both versions agree below .
20.7 Problem: The Calendar Module
Problem 20.1
Weekend problem — a module three times rewritten
The town’s date module now has three implementations behind one interface. The third keeps the dates in a sorted list and searches it by halving. The program below measures contains in all three, for , and dates.
import bisect
def empty():
"""Return a new set of dates, with no date in it."""
return []
def from_dates(dates):
"""Return a new set holding the dates of the iterable dates."""
return sorted(set(dates))
def add(s, d):
"""Add the date d to s; nothing changes if d is already in s."""
if not contains(s, d):
bisect.insort(s, d)
def contains(s, d):
"""Return True when the date d is in s."""
i = bisect.bisect_left(s, d)
return i < len(s) and s[i] == d
def size(s):
"""Return the number of dates in s."""
return len(s)
"""Time contains(s, d) in the three implementations, for n dates."""
import statistics
import time
from datetime import date, timedelta
import dateset_list
import dateset_set
import dateset_sorted
START = date(1800, 1, 1)
def per_lookup(ds, s, targets, runs=5, repeat=10):
times = []
for _ in range(runs):
begin = time.perf_counter()
for _ in range(repeat):
for d in targets:
ds.contains(s, d)
times.append((time.perf_counter() - begin) / (repeat * len(targets)))
return statistics.median(times)
if __name__ == "__main__":
print(f"{'n':>7} {'list':>10} {'sorted':>10} {'set':>10} (per lookup)")
for n in [1000, 10_000, 100_000]:
days = [START + timedelta(days=2 * i) for i in range(n)] # one day in two
targets = [days[-1], days[-1] - timedelta(days=1)] # present, absent
row = []
for ds in [dateset_list, dateset_sorted, dateset_set]:
s = ds.from_dates(days)
row.append(per_lookup(ds, s, targets))
print(f"{n:>7}", " ".join(f"{t * 1e6:8.2f} us" for t in row))
print(f"at n = 100000, the set is {row[0] / row[2]:,.0f} times faster",
"than the list")
$ python measure_dateset.py
n list sorted set (per lookup)
1000 5.72 us 0.24 us 0.06 us
10000 48.28 us 0.19 us 0.06 us
100000 501.27 us 0.23 us 0.06 us
at n = 100000, the set is 7,900 times faster than the list
contains measured on the author’s laptop (figures/measured_contains.py, a separate run). On both axes each step multiplies by . The list climbs in step with ; the two others stay flat.Part I — A module of dates.
- With the leap-year rule of chapter 1, how many days have the years , and ?
- What does
sizereturn for a set of dates holding every day of ? date(2027, 2, 29)raisesValueError: day is out of range for month. Why is this a good behaviour for a module of dates?- From the output of
stdlib_tour.py, on which day of the week is 20 November 2026, and which date comes days later?
Part II — The interface and its tests.
- List the five names of the interface, with the specification of each in one sentence.
- Which test checks that adding the same date twice keeps one copy?
- Why do the tests call only the five names of the interface?
- What should
python dateset_tests.py sortedprint? - Write one more test:
from_dates([])gives a set of size .
Part III — Three implementations.
- In
dateset_sorted, which function relies on the list being sorted, and which keeps it sorted? - For , how many dates does
containslook at, at most, in the list, and in the sorted list? - Why does
from_datesindateset_listusedict.fromkeysrather thanlist(dates)? - Why is
addslower thancontainsin the sorted implementation?
Part IV — Measured cost.
- By how much is the list’s time multiplied from to ? Is it what the count predicts?
- How do the sorted list and the set behave as grows?
- Predict the list’s time per lookup for .
- A program makes a thousand lookups in dates. How long does it take with each implementation?
- The measurement uses
from_datesto build the sets. Why not calls toadd? - Which lines of
use_dateset.pywould change to usedateset_sorted? - State the result: the speed-up of the set over the list at , and what happened to the tests.
Solution
Solution of Problem 20.1.
1. : divisible by , not a century year: days. : a century year not divisible by : . : divisible by : .
2. .
3. An impossible date is refused where it is made, with a message that names the problem, instead of entering a set silently and causing a wrong answer far away.
4. weekday() is : a Friday. days later is 28 February 2027.
5. empty() returns a new set with no date; from_dates(dates) returns a new set holding the dates given, each once; add(s, d) adds d to s, and does nothing if it is there; contains(s, d) tells whether d is in s; size(s) returns the number of dates in s.
6. test_add_twice.
7. So that they check only the promises, which every implementation must keep; a test using append would fail on a correct implementation with a set.
8. implementation: dateset_sorted, then the three lines ending in ok, the line of dashes and OK.
9.
def test_from_nothing(self):
self.assertEqual(ds.size(ds.from_dates([])), 0)
10. contains relies on it: bisect_left halves the list as binary search does, which is right only on a sorted list. from_dates sorts, and add inserts with insort at the right place.
11. The list: up to dates. The sorted list: .
12. list(dates) would keep repeated dates, and size would count them twice; dict.fromkeys keeps each date once, in the order of first appearance.
13. After the search, insort must make room: every later date moves one place, up to moves.
14. From to s: about times, for times more dates. The count predicts ; at small , the fixed cost of each call weighs more.
15. They hardly change: the sorted list stays near s ( dates looked at instead of ), the set near s.
16. About ten times more: ms per lookup.
17. The list, s, about half a second; the sorted list, about ms; the set, about ms.
18. Each add on the list scans it: calls look at about dates, for , far too long for a measurement; from_dates is linear.
19. The import lines and the list [dateset_list, dateset_set]; none of the lines using the dates.
20. At dates, the set answers contains about times faster than the list ( against s per lookup, on the author’s laptop), and the same tests pass, unchanged, on every implementation.