Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python namedtuple records: immutable fields can still hold mutable objects

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A namedtuple gives tuple positions named attributes without turning every referenced field value into an immutable object.

Download Python source kit

Operation contract

The receipt summary has a stable identifier and an immutable tuple of tags. Replacing its identifier returns a new record while retaining the old one. A second record intentionally contains a list to show that field assignment is blocked but the referenced list remains mutable. The type’s storage contract is distinct from a validated domain schema.

Failure and ownership boundary

Field type annotations or names do not validate values during construction. A namedtuple can be hashable only when its contents are hashable, and extending or changing positional fields can break callers that unpack it. Python dataclasses: frozen fields require an immutable value model and Python hash and equality: immutable dictionary keys cover alternatives and key requirements.

Working program

python
from collections import namedtuple

ReceiptSummary = namedtuple("ReceiptSummary", "receipt_id tags")
original = ReceiptSummary("R-0041", ("checked",))
updated = original._replace(receipt_id="R-0042")
print(original.receipt_id, updated.receipt_id)
mutable = ReceiptSummary("R-0043", [])
mutable.tags.append("packed")
print(mutable.tags)
try:
    mutable.receipt_id = "R-0044"
except AttributeError:
    print("field assignment rejected")

Output

Output
R-0041 R-0042
['packed']
field assignment rejected

Costs and limits

Replacing a k-field record creates a new outer tuple with O(k) reference work. Referenced objects are shared rather than recursively copied. For a fixed record shape, k is small; retaining many records still costs per-record storage.

Common Mistakes

  • Immutable outer fields do not freeze a contained list.
  • Construction does not enforce a business schema.

Connected lessons

Python tuples: immutable containers can still contain mutable state, Python dataclasses: frozen fields require an immutable value model, Python hash and equality: immutable dictionary keys.

python
namedtuple-records
Storage details