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
namedtuplefunction in thecollectionsmodule. - The
NamedTuplebase class in thetypingmodule. 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: floatThis 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...