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.
Python code
21 linesfrom 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
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
- Use `collections.namedtuple` if you don't need type hints.
- 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
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.