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 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 NamedTupleclass Point(NamedTuple):    latitude: float    longitude: floatclass Leg(NamedTuple):    start: Point    end: Point    distance: float

This changes the data structure from simple anonymous tuples to named tuples ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.