Python › Dataclasses & NamedTuples
How does typing.NamedTuple differ from collections.namedtuple in terms of syntax and type annotation support?
IntermediateAnswer
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 typeReal-world example Choosing typing.NamedTuple over collections.namedtuple specifically to get static type checking support in a typed codebase.