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 the collections module.
- The NamedTuple base class in the typing 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...