Classes
Structured Data Shapes
A dataclass is a normal class with __init__ and __repr__ generated from the annotated fields. Instances are mutable, support attribute access, and can carry methods like any other class.
Source
from dataclasses import dataclass
@dataclass
class UserClass:
name: str
score: int
a = UserClass("Ada", 98)
print(a)
a.score = 100
print(a.score)Output
UserClass(name='Ada', score=98)
100A NamedTuple is a tuple subclass with named positions. Instances are immutable, support both obj.field and obj[index], and the helper _replace produces a modified copy without mutating the original (since assigning to a field would fail).
Source
from typing import NamedTuple
class UserTuple(NamedTuple):
name: str
score: int
b = UserTuple("Ada", 98)
print(b)
print(b.name, b[1])
print(b._replace(score=100))Output
UserTuple(name='Ada', score=98)
Ada 98
UserTuple(name='Ada', score=100)A TypedDict is a plain dictionary at runtime. The annotations exist only for the type checker, so the value behaves like any dict — useful for JSON-shaped data that crosses an API boundary as a mapping.
Source
from typing import TypedDict
class UserDict(TypedDict):
name: str
score: int
c: UserDict = {"name": "Ada", "score": 98}
print(c)
print(c["name"])
print(type(c).__name__)Output
{'name': 'Ada', 'score': 98}
Ada
dictSame record, three runtime identities. The dataclass is its own class. The NamedTuple is literally a tuple. The TypedDict is literally a dict. That difference drives the choice: pick the form whose runtime behavior matches what the rest of the program already expects.
Source
print(isinstance(a, UserClass))
print(isinstance(b, tuple))
print(isinstance(c, dict))Output
True
True
TrueNotes
@dataclass— mutable, attribute access, methods; good default when behavior travels with data.typing.NamedTuple— immutable, attribute + index access, tuple semantics; good for small records that flow through unpacking.typing.TypedDict— runtime isdict, schema is type-checker-only; good for JSON-shaped data.collections.namedtupleis the older, untyped form ofNamedTuple; prefer thetypingversion in new code.
See also
- related: Dataclasses
- prerequisite: TypedDict
- prerequisite: Tuples
- related: Classes
Run the complete example
Expected output
UserClass(name='Ada', score=98)
100
UserTuple(name='Ada', score=98)
Ada 98
UserTuple(name='Ada', score=100)
{'name': 'Ada', 'score': 98}
Ada
dict
True
True
True
Execution time appears here after you run the example.