NamedTuple typed record in Python

Define a lightweight immutable record with type hints using typing.NamedTuple; access fields by name and unpack like a tuple.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Python code

21 lines
Python 3.9+
from typing import NamedTuple


class Point(NamedTuple):
    x: float
    y: float
    label: str = "origin"


if __name__ == "__main__":
    p = Point(3.5, -2.0, "A")
    print(p)
    print(f"x={p.x}, y={p.y}, label={p.label}")
    print("is tuple:", isinstance(p, tuple))

    q = Point(1.0, 1.0)
    print(q)

    # unpacking works like a regular tuple
    x, y, label = p
    print(f"unpacked: {x}, {y}, {label}")

Output

stdout
Point(x=3.5, y=-2.0, label='A')
x=3.5, y=-2.0, label=A
is tuple: True
Point(x=1.0, y=1.0, label='origin')
unpacked: 3.5, -2.0, A

How it works

typing.NamedTuple creates a tuple subclass with annotated fields and automatic _fields, _asdict(), and readable __repr__. Instances are immutable and support indexing, iteration, and unpacking just like regular tuples. Default values are allowed for later fields. Type hints help static checkers but are not enforced at runtime.

Common mistakes

  • Forgetting that NamedTuple is immutable — you cannot assign to fields after creation.
  • Using a mutable default (e.g., a list) — if needed, use a factory and `field(default_factory=...)`.
  • Confusing `NamedTuple` with a dataclass that has equality methods — NamedTuple equality is tuple-based.

Variations

  1. Use `collections.namedtuple` if you don't need type hints.
  2. Define a `@dataclass(frozen=True)` for similar immutable records with more control.

Real-world use cases

  • Representing a single database row or API response record with typed fields.
  • Returning multiple named values from a function where a dictionary would be less clear.
  • Carrying coordinates or other numeric pairs through processing code with readable names.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.