Rinaldo Fowler

How to use Python Named Tuples


I've been experimenting with using Named Tuples in Python for clarity. I like tuples because they're immutable, so I don't have to worry about side effects while manipulating them. I prefer them over dicts for this reason.

Named tuples allow me to explain in code what a tuple contains.

Here is how to invoke named tuples in python:

from collections import namedtuple

Point2D = namedtuple("Point2D", "x y")
specific_point = Point2D(3, 5)

I prefer the additional clarity provided by the typing module:

from typing import NamedTuple
class Point2D(NamedTuple):
    x: int
    y: int

specific_point = Point2D(3, 5)