Using named tuples to collect data
The third technique for collecting data into a complex structure is the named tuple. The idea is to create an object that is a tuple as well as a structure with named attributes. There are two variations available:
- The
namedtuple
function in thecollections
module. - The
NamedTuple
base class in thetyping
module. We'll use this almost exclusively because it allows explicit type hinting.
In the example from the previous section, we have nested namedtuple classes such as the following:
from typing import NamedTuple class Point(NamedTuple): latitude: float longitude: float class Leg(NamedTuple): start: Point end: Point distance: float
This changes the data structure from simple anonymous tuples to named tuples with type hints provided for each attribute. Here's an example:
>>> first_leg = Leg( ... Point(29.050501, -80.651169), ... Point(27.186001, -80.139503), ... 115.1751) >>> first_leg.start.latitude 29.050501
The first_leg...