Skip to content

Python namedtuple: Readable Immutable Records

  • What collections.namedtuple generates and why the result is still a real tuple.
  • How to use the helper API: _make, _asdict, _replace, _fields and _field_defaults.
  • How typing.NamedTuple adds type annotations, defaults and methods with class syntax.
  • The traps: tuple equality, shared mutable defaults, shallow immutability and super() in methods.
  • When a named tuple is the right record type and when a dataclass or a dict fits better.

collections.namedtuple() is a factory that builds a new subclass of tuple whose positions also have attribute names. An instance unpacks, indexes, hashes and compares exactly like the plain tuple it wraps, but order.total replaces order[2] and the repr shows name=value pairs. Instances have no per-instance __dict__, so they cost no more memory than an ordinary tuple. typing.NamedTuple creates the same kind of class from an annotated class body. Named tuples have been in the standard library since Python 2.6 and are fully current in Python 3.14.

Functions that return several values, CSV readers and database cursors all hand you tuples. A tuple is cheap and immutable, but its positions carry no meaning: the reader has to remember that index 2 is the total and index 3 is the status, and inserting a column silently shifts every index. A dict fixes readability but gives up immutability, hashing and tuple unpacking, and it costs more memory per record.

A named tuple keeps everything a tuple offers and adds names. The samples on this page run as plain scripts: save each one as a .py file and run it with python3 file.py. They were run on CPython 3.14.6; the output shown is from that run.

from collections import namedtuple
# Before: a plain tuple. What is row[2]? You have to remember.
row = ("ORD-1001", "ada@example.test", 59.90, "shipped")
print(row[2], row[3])
# After: same tuple, but every position has a name.
Order = namedtuple("Order", ["order_id", "email", "total", "status"])
order = Order("ORD-1001", "ada@example.test", 59.90, "shipped")
print(order.total, order.status)
print(order)
print(order == row, isinstance(order, tuple))

Output:

59.9 shipped
59.9 shipped
Order(order_id='ORD-1001', email='ada@example.test', total=59.9, status='shipped')
True True

The last line matters: a named tuple is a tuple, so it can replace one in existing code without breaking callers that unpack or index it.

The signature is namedtuple(typename, field_names, *, rename=False, defaults=None, module=None). field_names is a sequence of strings or one string separated by spaces or commas. Field names must be valid identifiers, must not be keywords and must not start with an underscore; the helper methods use a leading underscore precisely so they cannot clash with your fields. defaults applies to the rightmost fields.

from collections import namedtuple
# Field names as a list, or as one space/comma-separated string.
Order = namedtuple("Order", "order_id email total status", defaults=["pending"])
o = Order("ORD-1002", "lin@example.test", 120.0) # status uses its default
print(o)
print(Order._fields, Order._field_defaults)
# Tuple behavior: indexing, unpacking, len, iteration.
order_id, email, total, status = o
print(o[0], len(o), total)
# Build from any iterable, convert to dict, copy with changes.
row = ["ORD-1003", "sam@example.test", "15.5", "paid"]
o3 = Order._make(row)
print(o3._asdict())
print(o3._replace(status="refunded"))
# Immutable: assignment fails.
try:
o3.status = "shipped"
except AttributeError as exc:
print("AttributeError:", exc)
# Invalid names are rejected unless rename=True.
print(namedtuple("Row", ["id", "class", "id"], rename=True)._fields)

Output:

Order(order_id='ORD-1002', email='lin@example.test', total=120.0, status='pending')
('order_id', 'email', 'total', 'status') {'status': 'pending'}
ORD-1002 4 120.0
{'order_id': 'ORD-1003', 'email': 'sam@example.test', 'total': '15.5', 'status': 'paid'}
Order(order_id='ORD-1003', email='sam@example.test', total='15.5', status='refunded')
AttributeError: can't set attribute
('id', '_1', '_2')

Points worth knowing:

  • _make(iterable) builds an instance from any iterable, which is why it pairs well with map(Order._make, csv_reader). It does no type conversion: "15.5" stays a string.
  • _asdict() returns a regular dict (Python 3.8 changed it from OrderedDict).
  • _replace(**changes) returns a new instance. Since Python 3.13, copy.replace(o, status="refunded") does the same through the generic replace protocol.
  • _fields lets you build related types: namedtuple("AuditedOrder", Order._fields + ("audited_by",)).
  • For pickling, assign the class to a module-level name that matches typename.

typing.NamedTuple produces the same kind of class from annotations, which type checkers understand and humans read more easily. Fields with defaults must come after fields without them, and you can add docstrings, methods and properties.

from typing import NamedTuple
class OrderLine(NamedTuple):
"""One line on an OrdersPortal order."""
sku: str
quantity: int
unit_price: float = 0.0
@property
def line_total(self) -> float:
return round(self.quantity * self.unit_price, 2)
line = OrderLine("MUG-01", 3, 8.5)
print(line, line.line_total)
print(OrderLine("GIFT-CARD", 1))
print(OrderLine.__annotations__)
print(OrderLine.__mro__)

Output:

OrderLine(sku='MUG-01', quantity=3, unit_price=8.5) 25.5
OrderLine(sku='GIFT-CARD', quantity=1, unit_price=0.0)
{'sku': <class 'str'>, 'quantity': <class 'int'>, 'unit_price': <class 'float'>}
(<class '__main__.OrderLine'>, <class 'tuple'>, <class 'object'>)

The method resolution order shows that typing.NamedTuple is not a real base class: the generated class inherits straight from tuple. Annotations are documentation for type checkers; they are not enforced at run time.

An OrdersPortal job reads a CSV export, checks the header against the record type, aggregates revenue by status, applies a status change and returns the top orders as JSON.

import csv
import io
import json
from typing import NamedTuple
class OrderRow(NamedTuple):
order_id: str
email: str
total: float
status: str = "pending"
@classmethod
def from_csv(cls, fields: list[str]) -> "OrderRow":
order_id, email, total, *rest = fields
return cls(order_id, email, float(total), *rest)
EXPORT = """order_id,email,total,status
ORD-2001,ada@example.test,59.90,shipped
ORD-2002,lin@example.test,120.00,pending
ORD-2003,sam@example.test,15.50,shipped
ORD-2004,kim@example.test,240.00
"""
reader = csv.reader(io.StringIO(EXPORT))
header = next(reader)
assert tuple(header) == OrderRow._fields, "export columns changed"
orders = [OrderRow.from_csv(fields) for fields in reader]
# Group revenue by status: attribute access keeps this readable.
revenue: dict[str, float] = {}
for order in orders:
revenue[order.status] = revenue.get(order.status, 0) + order.total
print(revenue)
# Records are immutable, so a status change produces a new record.
orders = [o._replace(status="shipped") if o.order_id == "ORD-2004" else o
for o in orders]
# Sort by total (descending) and serialize the top two for an API response.
top = sorted(orders, key=lambda o: o.total, reverse=True)[:2]
print(json.dumps([o._asdict() for o in top], indent=2))
# A namedtuple serializes as a JSON array if you forget _asdict().
print(json.dumps(top[0]))

Output:

{'shipped': 75.4, 'pending': 360.0}
[
{
"order_id": "ORD-2004",
"email": "kim@example.test",
"total": 240.0,
"status": "shipped"
},
{
"order_id": "ORD-2002",
"email": "lin@example.test",
"total": 120.0,
"status": "pending"
}
]
["ORD-2004", "kim@example.test", 240.0, "shipped"]

The from_csv classmethod does the type conversion that _make does not, the missing status falls back to the default, and the header check turns a silent column shift into an immediate failure.

The following script shows the first four mistakes; its output is below it.

from collections import namedtuple
from typing import NamedTuple
Order = namedtuple("Order", "order_id total")
Refund = namedtuple("Refund", "order_id amount")
# 1. Equality is plain tuple equality: the type and field names are ignored.
print(Order("ORD-1", 10.0) == Refund("ORD-1", 10.0))
# 2. A mutable default is shared by every instance.
class Cart(NamedTuple):
owner: str
skus: list[str] = []
a, b = Cart("ada"), Cart("lin")
a.skus.append("MUG-01")
print(b.skus)
# 3. "Immutable" is shallow.
c = Cart("sam", ["PEN-02"])
c.skus.append("PEN-03")
print(c)
# 4. Unknown field in _replace raises TypeError (ValueError before 3.13).
try:
Order("ORD-1", 10.0)._replace(totl=12.0)
except (TypeError, ValueError) as exc:
print(type(exc).__name__, exc)
# 5. Field names cannot start with an underscore.
try:
namedtuple("Row", ["_id", "total"])
except ValueError as exc:
print("ValueError:", exc)

Output:

True
['MUG-01']
Cart(owner='sam', skus=['PEN-02', 'PEN-03'])
TypeError Got unexpected field names: ['totl']
ValueError: Field names cannot start with an underscore: '_id'
  • Comparing different record types. An Order and a Refund with the same values are equal and hash the same, so they collide as dict keys or set members. If type identity matters, use a dataclass, whose generated __eq__ checks the class.
  • Mutable defaults. A default is stored once and shared. Use None and build the list in a factory classmethod, or use a dataclass with field(default_factory=list).
  • Assuming deep immutability. The tuple cannot be rebound, but a list inside it can still change, and such an instance is no longer hashable.
  • Adding a field to a public record. Every caller that unpacks order_id, total = order or indexes by position breaks when a field is added. Named tuples make the positional API part of your contract.
  • Calling super() in a typing.NamedTuple method. It does not work: Python 3.11 to 3.13 fail at class creation with a confusing RuntimeError about __class__, and Python 3.14 raises TypeError: uses of super() and __class__ are unsupported in methods of NamedTuple subclasses. Call tuple.__repr__(self) directly instead.
  • Expecting type checks at run time. OrderLine("MUG-01", "3") is accepted; only a static type checker flags it.

Use a named tuple for small, fixed, immutable records that are naturally positional: rows from csv or sqlite3, multiple return values, dictionary keys made of several parts, and values you want to unpack. Reach for something else when the record needs validation, mutation, inheritance with new fields, or equality that respects the type.

Need Plain tuple namedtuple / NamedTuple @dataclass(frozen=True, slots=True) dict / TypedDict
Access by name No Yes Yes By key
Unpacking and indexing Yes Yes No (unless you add it) No
Immutable and hashable Yes Yes (shallow) Yes (shallow) No
Equality checks the type No No Yes No
Per-field default factories, validation hooks No No Yes (field, __post_init__) No
Memory per record Smallest Same as tuple Small with slots=True Largest
JSON Array Array (use _asdict()) Use dataclasses.asdict() Object

A useful rule: if you would be happy for the value to be a tuple, make it a named tuple; if you are designing an object, make it a dataclass.

Version Change
2.6 collections.namedtuple() added.
3.1 rename parameter.
3.6 module parameter; typing.NamedTuple class syntax with annotations (defaults, methods and docstrings from 3.6.1).
3.7 defaults parameter and _field_defaults; the verbose parameter and _source attribute removed.
3.8 _asdict() returns dict instead of OrderedDict.
3.11 Generic NamedTuple classes.
3.13 copy.replace() support; _replace() raises TypeError instead of ValueError for unknown fields. The keyword-argument form NamedTuple("NT", x=int) and omitting the fields argument are deprecated, to be disallowed in 3.15.
3.14 super() and __class__ in NamedTuple methods raise TypeError at class creation.

1. Is a named tuple instance larger than a plain tuple? No. The documentation states named tuple instances have no per-instance dictionary and need no more memory than regular tuples; sys.getsizeof reports the same size for both. Field names live on the class as descriptors, not on each instance.

2. Why do all the helper methods start with an underscore? To avoid clashing with field names. Field names cannot start with an underscore, so _replace, _asdict, _make and _fields can never be shadowed by a field called replace or fields.

3. How do you add a computed attribute without adding memory per instance? Subclass the generated type, set __slots__ = () so the subclass does not reintroduce an instance __dict__, and add a @property. With typing.NamedTuple, put the property in the class body; the generated class already has no instance dictionary.

4. Senior scenario: OrdersPortal’s public SDK returns Order as a named tuple, and the product team wants to add a currency field. What do you do? Adding a field changes len(), breaks positional unpacking in client code and changes equality with plain tuples, so it is a breaking change even with a default. Options: ship it in a major version; or keep Order stable and add a new type (a frozen dataclass, or OrderV2 built from Order._fields + ("currency",)) returned by a new method. For future records that are not truly positional, choose a frozen dataclass from the start, because it can gain keyword-only fields with defaults without breaking callers.

5. Why does json.dumps turn a named tuple into a list? The encoder sees a tuple subclass and encodes it as a JSON array before any custom default hook runs. Convert explicitly with _asdict() when you want an object.

  • A named tuple is a real tuple subclass with attribute names: same memory, same unpacking, better readability.
  • Use typing.NamedTuple for typed fields, defaults, docstrings and methods; avoid super() in those methods.
  • _make, _asdict, _replace and _fields cover construction, serialization, copying and introspection.
  • Equality ignores the type, immutability is shallow, and adding a field breaks positional callers.
  • Prefer a frozen dataclass when you are designing an object rather than labeling a tuple.
  • Tuples: the immutable sequence that named tuples extend.
  • collections module: overview of namedtuple, deque, Counter, defaultdict and OrderedDict.
  • dataclasses: the alternative for richer, mutable or type-strict records.
  • OrderedDict: what _asdict() used to return before Python 3.8.
  • __slots__: how named tuples avoid a per-instance __dict__.
  • Type hints: annotations used by typing.NamedTuple.