Compound data 0/1

Lesson 17 of 21

Compound data

Group values into one, hide how they are stored, and build linked lists and trees.

Part 1 of 8 Records

Keeping facts about one thing together

A mountain has a name and a height. Here are four of the highest mountains in Japan, and we want to print them from highest to lowest. A first attempt keeps the names in one list and the heights in another, so that position i in both lists describes the same mountain, and sorts the heights:

Sign up to run
names = ['Kita', 'Aino', 'Fuji', 'Okuhotaka']
heights = [3193, 3189, 3776, 3190]
heights.sort(reverse=True)
for i in range(4):
    print(names[i], heights[i])

The heights come out in the right order, but the program says Kita is 3776 m high, which is the height of Fuji. Sorting moved the heights and left the names where they were, so position i no longer describes one mountain.

The fix is to make each mountain a single value that holds both facts. Then wherever a mountain moves, its name moves with it. A value built from several values is called compound data, and this lesson is about building it and working with it.

Records with named parts

A record is a compound value that describes one thing, with one named part, called a field, for each fact about it. In Python you define a kind of record with a data class: a class statement that names the new type, the line @dataclass above it, and the fields listed inside, each with its type after a colon. A class statement can hold much more than fields, but for a record this pattern is all you need.

Mountain('Fuji', 3776) builds a record, and fuji.name and fuji.height read its fields:

Sign up to run
@dataclass
class Mountain:
    name: str
    height: int

fuji = Mountain('Fuji', 3776)
print(fuji.name, fuji.height)
print(fuji)
print(fuji == Mountain('Fuji', 3776))
Python details

from dataclasses import dataclass brings dataclass in from Python's standard library, the way import sys brings in sys.

@dataclass writes the constructor, the function that Mountain(...) calls to build a record. It also writes the text print shows for a record, and ==, which compares two records field by field.

Python does not check the types after the colons; they record what each field should hold.

A data class is a type, as int and str are: you can keep Mountain values in a list, pass one to a function and return one. Here is the sorting program again with one list of records. Python doesn't know how to compare two mountains, and sort with no key stops with TypeError: '<' not supported between instances of 'Mountain' and 'Mountain', so the key says what to sort by:

Sign up to run
@dataclass
class Mountain:
    name: str
    height: int

mountains = [Mountain('Kita', 3193), Mountain('Aino', 3189), Mountain('Fuji', 3776), Mountain('Okuhotaka', 3190)]
mountains.sort(key=lambda m: m.height, reverse=True)
for m in mountains:
    print(m.name, m.height)

Now every name stays with its height.

Records or tuples

A tuple per mountain, ('Fuji', 3776), would also have fixed the program. A tuple is compound data too. The difference is that its parts are numbered rather than named: m[1] doesn't say what it holds, while m.height does. With two parts that hardly matters. With four parts, read in a dozen places, the names keep a program readable, and the Data abstraction part below shows a bug that numbered parts make easy to write.

Tuples can do two things a plain data class can't. They compare part by part, so a list of tuples sorts with no key. And they are hashable, so a tuple can be a set element or a dictionary key, while putting a Mountain in a set stops with a TypeError saying the type is unhashable. Writing @dataclass(frozen=True) instead of @dataclass makes the records unchangeable, and then they can go in a set too.

So a tuple suits a small value used in one place, such as a sort key or a name to look up in a set, and a record suits a value that travels through several functions. Two problems to practise on: the first is the mountain program with input to read, and in the second, a set of (family name, given name) tuples finds whether two people share a name.