python namedtuple vs dataclass: When to Use Each
Python's namedtuple and dataclass both create lightweight objects with named fields. They differ in mutability, type hints, memory footprint, defaults, and extensibility; see when to use each.

When you need a lightweight object that holds a fixed set of named fields, Python gives you two standard-library options: namedtuple from collections and the @dataclass decorator from dataclasses. Both produce objects with readable field access, but they differ in mutability, type handling, memory usage, and extensibility. Choosing between them depends on how much flexibility you need versus how much overhead you want.
The Core Difference in One Example
from collections import namedtuple
from dataclasses import dataclass
Point = namedtuple("Point", ["x", "y"])
@dataclass
class PointDC:
x: int
y: int
p1 = Point(3, 4)
p2 = PointDC(3, 4)
print(p1.x, p1.y) # 3 4
print(p2.x, p2.y) # 3 4Both Point and PointDC give you .x and .y field access, a readable repr, and structural equality. The differences appear when you try to modify a field, add a default, or extend the structure.
Syntax: How Each Structure Is Declared
namedtuple is a factory function. You call it with a type name and a list of field names, and it returns a new tuple subclass.
Color = namedtuple("Color", ["red", "green", "blue"])
c = Color(255, 0, 128)dataclass is a class decorator. You write a normal class with annotated fields, and the decorator generates __init__, __repr__, __eq__, and optionally other dunder methods.
@dataclass
class Color:
red: int
green: int
blue: intThe syntax difference matters for readability. A namedtuple declaration reads like a compact data definition. A dataclass reads like a regular class, which makes it easier to add methods, properties, or custom __post_init__ logic without leaving the class body.
Mutability and Field Assignment
A namedtuple is immutable. Once created, you cannot assign to a field:
c = Color(255, 0, 128)
c.red = 0 # AttributeError: can't set attributeTo change a value, you use _replace(), which returns a new instance:
c2 = c._replace(red=0)A dataclass is mutable by default:
c = Color(255, 0, 128)
c.red = 0 # worksIf you need immutability, pass frozen=True:
@dataclass(frozen=True)
class Color:
red: int
green: int
blue: intFrozen dataclasses raise FrozenInstanceError on assignment, similar to a namedtuple. However, frozen dataclasses do not provide _replace(); you must rebuild the instance manually or use dataclasses.replace().
Type Hints, Defaults, and Validation
collections.namedtuple itself does not have an annotation syntax. If you want a named-tuple-style class with field annotations, use typing.NamedTuple:
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: intThe annotations are stored in Point.__annotations__ and can be used by type checkers, but they are not enforced at runtime.
Dataclasses treat class-level annotations as their field declarations. You can also use field() to control defaults, default_factory for mutable defaults, and __post_init__ for validation.
from dataclasses import dataclass, field
@dataclass
class Config:
host: str
port: int = 8080
tags: list = field(default_factory=list)
def __post_init__(self):
if not 0 <= self.port <= 65535:
raise ValueError(f"Invalid port: {self.port}")namedtuple supports default values since Python 3.7, but only through the defaults keyword argument:
Config = namedtuple("Config", ["host", "port", "tags"], defaults=["localhost", 8080, []])The default list is shared across instances, which is a classic mutable-default bug. A dataclass's default_factory parameter avoids that problem by creating a fresh list per instance.
Memory Footprint and Runtime Behavior
A namedtuple is a tuple subclass, so it stores its fields in a compact tuple layout. This makes it memory-efficient and fast to construct, especially for large numbers of small objects.
By default, a dataclass instance stores fields as instance attributes in __dict__, which is a dictionary. That adds memory overhead per instance. If you want to reduce that, use @dataclass(slots=True) in Python 3.10+:
@dataclass(slots=True)
class Point:
x: int
y: intSlots remove the per-instance __dict__, bringing memory usage closer to a namedtuple while keeping dataclass features. Slots require care with inheritance and change behavior for features such as weak references.
For the common case of a few thousand objects, the difference is negligible. For millions of objects, namedtuple or a slotted dataclass is the right choice.
Extending and Reusing the Structures
namedtuple subclasses are tuples, so they support tuple operations like indexing and unpacking. You can also add methods by subclassing:
class Point(namedtuple("Point", ["x", "y"])):
def distance_from_origin(self):
return (self.x ** 2 + self.y ** 2) ** 0.5Dataclasses are regular classes, so you can use inheritance, mixins, properties, and custom methods directly. You can also make a dataclass a subclass of another dataclass:
@dataclass
class Base:
id: int
@dataclass
class User(Base):
name: strInheritance with namedtuple is possible but awkward because field order and defaults interact with the tuple layout.
Choosing Between namedtuple and dataclass
Use namedtuple when:
- You need a lightweight, immutable record with tuple semantics (indexing, unpacking, and hashability when fields are hashable).
- The structure is simple and will not grow validation or methods.
- Memory efficiency matters and you are creating many instances.
- You want to interoperate with code that expects a tuple.
Use dataclass when:
- You need mutable fields or
frozen=Truefor immutability. - You want type hints, defaults,
default_factory, and__post_init__validation. - You plan to extend the structure with methods, properties, or inheritance.
- You want to control field metadata with
field().
| Feature | namedtuple | dataclass |
|---|---|---|
| Mutability | Immutable | Mutable by default; frozen=True for immutability |
| Type hints | No annotation syntax in collections.namedtuple; typing.NamedTuple stores hints | Annotations are field declarations |
| Default values | Supported since Python 3.7 | field(default=...) |
| Mutable defaults | Shared across instances | default_factory creates fresh instances |
| Memory footprint | Compact tuple layout | __dict__ per instance; slots=True reduces it |
| Inheritance | Awkward | Native class inheritance |
| Validation | None built-in | __post_init__ |
A good rule of thumb: if you only need a named record with fixed fields and no behavior, namedtuple is sufficient. If you need validation, defaults, mutability, or inheritance, dataclass is the better fit. For large-scale data processing where memory matters, a slotted dataclass gives you the best of both.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.