Classes

Structured Data Shapes

dataclass, NamedTuple, and TypedDict each model records with different trade-offs.

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)
100
dataclassmutable attrsNamedTupletuple + namesTypedDictdict at runtime
The same record can be a mutable dataclass, an immutable NamedTuple, or a runtime dict described by TypedDict.

A 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
dict

Same 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
True

Notes

See also

Run the complete example

Example code

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.