7.2 Using NamedTuple to collect data
The second technique for collecting data into a complex structure is typing.NamedTuple. The idea is to create a class that is an immutable tuple 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 following examples, we’ll use nested NamedTuple classes such as the following:
from typing import NamedTuple 
 
class PointNT(NamedTuple): 
    latitude: float 
    longitude: float 
 
class LegNT(NamedTuple): 
    start: PointNT 
    end: PointNT 
    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...