Ben Chuanlong Du's Blog

It is never too late to learn.

Dataclass vs namedtuple in Python

Tips and Traps

  1. Prefer Dataclass to namedtuple for many reasons.

    • A namedtuple is immutable while a dataclass can be both mutable (frozen=False which is the default) or immutable (frozen=True).

      However, namedtuple does have one advantage over dataclass. Members of a namedtuple is assible both via the dot operator and index. In situations where both dot accessing and index accessing of members is required, a namedtuple comes handy. For examples, a list of namedtuple objects can be used as the data for creating a pandas DataFrame but not a list of dataclass objects.