---
title: "Modules, Interfaces and Libraries"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 20
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 20 — Modules, Interfaces and Libraries

Twenty programs of the town hall use the same small [module](#def-g11-modules-and-interfaces-module) of dates: the school calendar, the [library](#def-g11-modules-and-interfaces-library)’s loans, the market’s opening days. One summer the [module](#def-g11-modules-and-interfaces-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](#def-g11-modules-and-interfaces-module) promised, never on how it kept its dates. This chapter splits programs into [modules](#def-g11-modules-and-interfaces-module), separates the promise from the way it is kept, reads the documentation of Python’s own [modules](#def-g11-modules-and-interfaces-module), and then changes an [implementation](#def-g11-modules-and-interfaces-interface) 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](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#ch-g10-specifications-and-tests)); a set answers `x in s` without a scan (chapter [2](https://one-course.com/books/computer-science/2/en/chapter/2-tuples-sets-and-comprehensions#ch-g10-tuples-sets-comprehensions)); the [number of halvings](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-halvings) $h(n)$ and the cost of searching (chapter [17](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#ch-g11-cost-of-an-algorithm)).

## 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`.

```python
"""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
```

***Listing 20.1.** A [module](#def-g11-modules-and-interfaces-module) of plane geometry: two functions and a helper. code/grade-11/09-modules-and-interfaces/listings/geometry.py*

`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.

```python
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("__")])
```

***Listing 20.2.** Two ways of importing, and the names a [module](#def-g11-modules-and-interfaces-module) holds. code/grade-11/09-modules-and-interfaces/listings/use_geometry.py*

```
$ python use_geometry.py
5.0
12.0
module: geometry | this program: __main__
names in geometry: ['_square', 'distance', 'math', 'perimeter']
```

***Output 20.1.** The [module](#def-g11-modules-and-interfaces-module) also holds `math`, which it imported for itself, and the helper `_square`.*

Python looks for a [module](#def-g11-modules-and-interfaces-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](#def-g11-modules-and-interfaces-module); the list is in `sys.path`. A [module](#def-g11-modules-and-interfaces-module) named like one of Python’s own, `random.py` next to a program, hides the real one: a classic trap.

Each [module](#def-g11-modules-and-interfaces-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.

```python
"""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"))
```

***Listing 20.3.** A [module](#def-g11-modules-and-interfaces-module) with a guarded demonstration. code/grade-11/09-modules-and-interfaces/listings/main_guard.py*

```
$ python main_guard.py
main_guard is running as __main__
hello, ada
```

***Output 20.2.** Started as a program: the guard lets the greeting through.*

```
$ python import_guard.py
main_guard is running as main_guard
hello, Brenmoor
```

***Output 20.3.** Imported by `import_guard.py`, which calls `greet` itself: the [module](#def-g11-modules-and-interfaces-module)’s own greeting does not run.*

A [module](#def-g11-modules-and-interfaces-module)’s statements run only at its first import; a second `import` in the same run finds it already loaded.

![The modules of this chapter’s date programs. An arrow goes from a module to a module it imports; the grey ones come with Python.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-modules-and-interfaces/fig-49bee6dc1f5a.svg)

*The [modules](#def-g11-modules-and-interfaces-module) of this chapter’s date programs. An arrow goes from a [module](#def-g11-modules-and-interfaces-module) to a [module](#def-g11-modules-and-interfaces-module) it imports; the grey ones come with Python.*

## 20.2 The interface and the hidden implementation

**Definition 20.2 (Interface, implementation).**

The *interface* of a [module](#def-g11-modules-and-interfaces-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](#def-g11-modules-and-interfaces-module): helpers, data structures, imported [modules](#def-g11-modules-and-interfaces-module).

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](#def-g11-modules-and-interfaces-module) only imported for itself, as `geometry.math`, is internal too.

The documentation of a function is its [docstring](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-docstring), which `help` prints.

```python
import geometry

help(geometry.perimeter)
```

***Listing 20.4.** Asking for the documentation of a function. code/grade-11/09-modules-and-interfaces/listings/help_view.py*

```
$ 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.
```

***Output 20.4.** The signature and the [docstring](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-docstring): all a user needs.*

![The interface as a wall. Above it, five names with their specifications, the same in the three modules; below it, three ways of keeping the dates, which users never see.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-modules-and-interfaces/fig-6453fc6a3827.svg)

*The [interface](#def-g11-modules-and-interfaces-interface) as a wall. Above it, five names with their specifications, the same in the three [modules](#def-g11-modules-and-interfaces-module); below it, three ways of keeping the dates, which users never see.*

## 20.3 The standard library and its documentation

**Definition 20.3 (Library, standard library).**

A *library* is a collection of [modules](#def-g11-modules-and-interfaces-module) 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](#def-g11-modules-and-interfaces-interface), of a [library](#def-g11-modules-and-interfaces-library) is its [interface](#def-g11-modules-and-interfaces-interface): the names, with their specifications, that programs may use.

Python’s [standard library](#def-g11-modules-and-interfaces-library) has hundreds of [modules](#def-g11-modules-and-interfaces-module), 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.

![The parts of a documentation entry, on the entry for statistics.median, shortened. Reading the raised exceptions and the examples is part of reading the entry.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-modules-and-interfaces/fig-e27baa3d8087.svg)

*The parts of a documentation entry, on the entry for `statistics.median`, shortened. Reading the raised exceptions and the examples is part of reading the entry.*

```python
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)
```

***Listing 20.5.** Four [modules](#def-g11-modules-and-interfaces-module) of the [standard library](#def-g11-modules-and-interfaces-library), used after reading their entries. code/grade-11/09-modules-and-interfaces/listings/stdlib_tour.py*

```
$ 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
```

***Output 20.5.** A choice, two medians, the three most common letters, and some dates.*

Each line of the output is explained by an entry:

- `random.choice` returns an element of a non-empty sequence, and raises `IndexError` on an empty one. The documentation also warns that, for a given seed, only `random()` itself is guaranteed to give the same numbers in every version of Python; `choice` may change.
- `statistics.median` of an even number of values is the mean of the two middle ones, here $(3 + 4) / 2$ .
- `Counter.most_common` lists equal counts in the order first met: `b` before `r` .
- `date.weekday()` numbers Monday $0$ to Sunday $6$ : $4$ is a Friday. Subtracting two dates gives a `timedelta` , here $42$ days; years run from $1$ to $9999$ .

**Remark 20.5.**

The documentation is written for one version of Python. The entries of this book were read for version $3.12$; 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](#def-g11-modules-and-interfaces-module) of dates of the town hall, met at the start of the chapter, offers five functions. Its first [implementation](#def-g11-modules-and-interfaces-interface) keeps the dates in a list.

```python
"""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)
```

***Listing 20.6.** A set of dates kept in a list. code/grade-11/09-modules-and-interfaces/listings/dateset_list.py*

The second keeps them in a Python set; only the bodies change, and they become shorter.

```python
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)
```

***Listing 20.7.** The same [interface](#def-g11-modules-and-interfaces-interface), kept in a set (lines 1–4, the [module](#def-g11-modules-and-interfaces-module)’s [docstring](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-docstring), are not shown). code/grade-11/09-modules-and-interfaces/listings/dateset_set.py*

```python
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)))
```

***Listing 20.8.** A user of the [interface](#def-g11-modules-and-interfaces-interface), run with each [implementation](#def-g11-modules-and-interfaces-interface). code/grade-11/09-modules-and-interfaces/listings/use_dateset.py*

```
$ python use_dateset.py
dateset_list size 3 | 25 December: True | 24 December: False
dateset_set size 3 | 25 December: True | 24 December: False
```

***Output 20.6.** The same answers from both: the second 1 May was not added twice.*

The tests are written against the [interface](#def-g11-modules-and-interfaces-interface) only, and the same file tests every [implementation](#def-g11-modules-and-interfaces-interface), named on the command line.

```python
"""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)
```

***Listing 20.9.** The tests of the [interface](#def-g11-modules-and-interfaces-interface): one file for every [implementation](#def-g11-modules-and-interfaces-interface). code/grade-11/09-modules-and-interfaces/listings/dateset_tests.py*

```
$ 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
```

***Output 20.7.** The same three tests pass on both [implementations](#def-g11-modules-and-interfaces-interface) (the line with the running time is filtered out).*

**Method 20.6 (Changing an implementation safely).**

1. Write the [interface](#def-g11-modules-and-interfaces-interface) down: the names and the specification of each, in [docstrings](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-docstring) .
2. Write tests that use the [interface](#def-g11-modules-and-interfaces-interface) only, and check that they pass on the old [implementation](#def-g11-modules-and-interfaces-interface) .
3. Write the new [implementation](#def-g11-modules-and-interfaces-interface) with the same names and specifications.
4. Run the same tests on it. Users need change nothing but, at most, the name of the [module](#def-g11-modules-and-interfaces-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](#def-g11-modules-and-interfaces-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](#def-g11-modules-and-interfaces-interface)), its licence (what it allows), and whether it is still maintained. This book installs nothing: every program in it uses the [standard library](#def-g11-modules-and-interfaces-library) only.

Languages differ in their spelling, much less in their constructions. The same few constructions appear in the toy machine’s [assembly language](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) of chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine) 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 of Exercise 20.1.**

`geometry.distance((0, 0), (1, 1))` works and returns $\sqrt{2}$. `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](#def-g11-modules-and-interfaces-module) that `geometry` imported for itself, an [implementation](#def-g11-modules-and-interfaces-interface) 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 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](#def-g11-modules-and-interfaces-module) defines `MAX_SIZE`, `_cache`, `load`, `_parse` and `save`, and imports `json`. Which names belong to its [interface](#def-g11-modules-and-interfaces-interface)?

**Solution of Exercise 20.3.**

`MAX_SIZE`, `load` and `save`, provided they are documented. `_cache` and `_parse` are internal by their underscore; `json` is a [module](#def-g11-modules-and-interfaces-module) imported for the [module](#def-g11-modules-and-interfaces-module)’s own use.

**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 of Exercise 20.4.**

Sorted, the values are $1, 3, 7, 9$; 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](#def-g11-modules-and-interfaces-module) `temperature` with two functions, `to_fahrenheit(c)` and `to_celsius(f)`, each with a [docstring](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-docstring). (Fahrenheit is Celsius times $9/5$, plus $32$.)

**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 $100$ against $212$ and that $-40$ 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 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](#def-g11-modules-and-interfaces-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](#def-g11-modules-and-interfaces-module) that each need the other at import time form a cycle. Correction: put `FIRST_STOP` in a third [module](#def-g11-modules-and-interfaces-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 of Exercise 20.7.**

The user’s: the [interface](#def-g11-modules-and-interfaces-interface) never promised a list, and `sort` and `[0]` rely on the [implementation](#def-g11-modules-and-interfaces-interface). The set has no `sort` and no index. The right way is to ask the [module](#def-g11-modules-and-interfaces-module)’s author for a function in the [interface](#def-g11-modules-and-interfaces-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 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 $100$ random polygons.

**Exercise 20.9 ★★.**

For $n$ dates, how many dates do `add` and `contains` look at, at most, in `dateset_list`? What about `dateset_set`?

**Solution of Exercise 20.9.**

In `dateset_list`, `contains` compares with up to $n$ 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 $n$ (chapter [17](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#ch-g11-cost-of-an-algorithm)).

**Exercise 20.10 ★★.**

What does this print, and why? `print(pow(2, 10))`, then `from math import *`, then again `print(pow(2, 10))`.

**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 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 $n = 3$: `[('the', 4), ('cat', 2), ('saw', 2)]`; `cat` comes before `saw` and `dog`, met first.

**Exercise 20.12 ★★★.**

Design, in prose, the [interface](#def-g11-modules-and-interfaces-interface) of a [module](#def-g11-modules-and-interfaces-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 of Exercise 20.12.**

One possible [interface](#def-g11-modules-and-interfaces-interface):

- `new_queue()` : returns a new empty queue;
- `push(q, x)` : adds `x` at the end of `q` ;
- `pop(q)` : removes and returns the element at the front, the earliest pushed of those still there; on an empty queue it raises `IndexError` and leaves the queue unchanged;
- `is_empty(q)` : returns `True` when `q` holds no element;
- `size(q)` : returns the number of elements of `q` .

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](#def-g11-modules-and-interfaces-module) `dates_chosen` that offers the five names of the [interface](#def-g11-modules-and-interfaces-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 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](#def-g11-modules-and-interfaces-interface) changes from list to set, and when the [interface](#def-g11-modules-and-interfaces-interface) renames `contains` to `has`.

**Solution of Exercise 20.14.**

[Implementation](#def-g11-modules-and-interfaces-interface) changed, [interface](#def-g11-modules-and-interfaces-interface) kept: no line of the twenty programs changes, or at most the import line of each, $20$ lines, if the [module](#def-g11-modules-and-interfaces-module)’s name changes. [Interface](#def-g11-modules-and-interfaces-interface) changed: each of the $20 \times 10 = 200$ calls is rewritten, in programs written by others, and any missed one fails only when it runs. A change behind the [interface](#def-g11-modules-and-interfaces-interface) costs the [module](#def-g11-modules-and-interfaces-module)’s author alone; a change of the [interface](#def-g11-modules-and-interfaces-interface) costs every user.

**Exercise 20.15 ★★★.**

The [module](#def-g11-modules-and-interfaces-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](#def-g11-modules-and-interfaces-module) so that the work is done only when a prime is first asked for.

**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 $2000$.

## 20.7 Problem: The Calendar Module

**Problem 20.1.**

Weekend problem — a module three times rewritten

The town’s date [module](#def-g11-modules-and-interfaces-module) now has three [implementations](#def-g11-modules-and-interfaces-interface) behind one [interface](#def-g11-modules-and-interfaces-interface). The third keeps the dates in a sorted list and searches it by halving. The program below measures `contains` in all three, for $n = 10^3$, $10^4$ and $10^5$ dates.

```python
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)
```

***Listing 20.10.** The third [implementation](#def-g11-modules-and-interfaces-interface): a sorted list. code/grade-11/09-modules-and-interfaces/listings/dateset_sorted.py*

```python
"""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")
```

***Listing 20.11.** One lookup, three [implementations](#def-g11-modules-and-interfaces-interface). code/grade-11/09-modules-and-interfaces/listings/measure_dateset.py*

```
$ 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
```

***Output 20.8.** Measured on the author’s laptop, in microseconds per lookup.*

![contains measured on the author’s laptop (figures/measured_contains.py, a separate run). On both axes each step multiplies by 10. The list climbs in step with n; the two others stay flat.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-modules-and-interfaces/fig-470e70943515.svg)

*`contains` measured on the author’s laptop (`figures/measured_contains.py`, a separate run). On both axes each step multiplies by $10$. The list climbs in step with $n$; the two others stay flat.*

**Part I — A module of dates.**

1. With the leap-year rule of chapter [1](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#ch-g10-specifications-and-tests) , how many days have the years $2028$ , $2100$ and $2000$ ?
2. What does `size` return for a set of dates holding every day of $2028$ ?
3. `date(2027, 2, 29)` raises `ValueError: day is out of range for month` . Why is this a good behaviour for a [module](#def-g11-modules-and-interfaces-module) of dates?
4. From the output of `stdlib_tour.py` , on which day of the week is 20 November 2026, and which date comes $100$ days later?

**Part II — The interface and its tests.**

5. List the five names of the [interface](#def-g11-modules-and-interfaces-interface) , with the specification of each in one sentence.
6. Which test checks that adding the same date twice keeps one copy?
7. Why do the tests call only the five names of the [interface](#def-g11-modules-and-interfaces-interface) ?
8. What should `python dateset_tests.py sorted` print?
9. Write one more test: `from_dates([])` gives a set of size $0$ .

**Part III — Three implementations.**

10. In `dateset_sorted` , which function relies on the list being sorted, and which keeps it sorted?
11. For $n = 10^5$ , how many dates does `contains` look at, at most, in the list, and in the sorted list?
12. Why does `from_dates` in `dateset_list` use `dict.fromkeys` rather than `list(dates)` ?
13. Why is `add` slower than `contains` in the sorted [implementation](#def-g11-modules-and-interfaces-interface) ?

**Part IV — Measured cost.**

14. By how much is the list’s time multiplied from $n = 10^3$ to $n = 10^5$ ? Is it what the count predicts?
15. How do the sorted list and the set behave as $n$ grows?
16. Predict the list’s time per lookup for $n = 10^6$ .
17. A program makes a thousand lookups in $10^5$ dates. How long does it take with each [implementation](#def-g11-modules-and-interfaces-interface) ?
18. The measurement uses `from_dates` to build the sets. Why not $n$ calls to `add` ?
19. Which lines of `use_dateset.py` would change to use `dateset_sorted` ?
20. State the result: the speed-up of the set over the list at $n = 10^5$ , and what happened to the tests.

**Solution of Problem 20.1.**

**1.** $2028$: divisible by $4$, not a century year: $366$ days. $2100$: a century year not divisible by $400$: $365$. $2000$: divisible by $400$: $366$.

**2.** $366$.

**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 $4$: a Friday. $100$ 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](#def-g11-modules-and-interfaces-interface) must keep; a test using `append` would fail on a correct [implementation](#def-g11-modules-and-interfaces-interface) 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 $100\,000$ dates. The sorted list: $h(10^5) + 1 = 17$.

**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 $n$ moves.

**14.** From $5.72$ to $501.27$ $\mu$s: about $88$ times, for $100$ times more dates. The count predicts $100$; at small $n$, the fixed cost of each call weighs more.

**15.** They hardly change: the sorted list stays near $0.2$ $\mu$s ($17$ dates looked at instead of $10$), the set near $0.06$ $\mu$s.

**16.** About ten times more: $5$ ms per lookup.

**17.** The list, $1000 \times 501$ $\mu$s, about half a second; the sorted list, about $0.23$ ms; the set, about $0.06$ ms.

**18.** Each `add` on the list scans it: $n$ calls look at about $n^2/2$ dates, $5 \times 10^9$ for $n =
10^5$, 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 $n = 10^5$ dates, **the set answers `contains` about $7900$ times faster than the list** ($0.06$ against $501$ $\mu$s per lookup, on the author’s laptop), and **the same tests pass, unchanged, on every [implementation](#def-g11-modules-and-interfaces-interface)**.
