Named Tuples via typing.NamedTuple
Explore how to create and use named tuples in Python with typing.NamedTuple. Learn to define immutable data groups with named attributes, access values by name, and add methods for computed properties. This lesson helps you use named tuples effectively while leveraging type hints and immutability.
We'll cover the following...
Why do we need named tuples?
So, what do we do when we want to group values together but know we will frequently need to access them individually? There are actually several options, including these:
-
We can use an empty
objectinstance. We can assign arbitrary attributes to this object. But without a good definition of what’s allowed and what types are expected, we’ll have trouble understanding this. And we’ll get a lot of mypy errors. -
We can use a dictionary. This can work out nicely, and we can formalize the acceptable list of keys for the dictionary with
typing.TypedDicthint. -
We can use a
@dataclass. -
We can also provide names to the positions of a tuple. While we’re at it, we can also define methods for these named tuples, making them super helpful.
Named tuples are tuples with attitude. They are a great way to create an immutable grouping of data values. When we define a named ...