Python — From Basics to Advanced · Dataclasses and Enums
Choosing: dataclass vs namedtuple vs pydantic vs plain class
Dataclasses and Enums
Introduction
Python offers several ways to model a "data record": tuple, namedtuple (collections), typing.NamedTuple, dataclass (3.7+), TypedDict (typing), pydantic.BaseModel (third party), attrs (third party), and a plain class. Each has different strengths: namedtuple — immutability and tuple interop; dataclass — boilerplate-free in the stdlib, mutable by default; TypedDict — type hints for plain dicts without runtime checks; pydantic — runtime type validation and JSON parsing, perfect for APIs; attrs — the spiritual predecessor of dataclass with extra options. This lesson is about choosing.