Python › Dataclasses & NamedTuples

How does typing.NamedTuple differ from collections.namedtuple in terms of syntax and type annotation support?

Intermediate

Answer

typing.NamedTuple uses a class-based syntax with type ANNOTATIONS for each field (readable by type checkers like mypy), while collections.namedtuple uses a functional call with a string/list of field names and no built-in type information — both produce the same underlying immutable, tuple-based result at runtime.
from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int

p = Point(1, 2)
print(p.x)  # 1, with full type-checker support for the 'x' field's type
Real-world example Choosing typing.NamedTuple over collections.namedtuple specifically to get static type checking support in a typed codebase.

Common follow-ups: Can typing.NamedTuple fields also have default values, similar to a dataclass?