Data containers
Python has many ways to hold a record such as a user, an order or a config. This page shows when to use each one, then the options of @dataclass and __slots__.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| a record class without boilerplate | @dataclass |
@dataclass class User: name: str |
| a default value | name: type = value |
retries: int = 3 |
| a fresh list or dict per instance | field(default_factory=list) |
tags: list[str] = field(default_factory=list) |
validate or normalize after __init__ |
__post_init__ |
if self.port < 1: raise ValueError(...) |
| a field computed from others | field(init=False) + __post_init__ |
total: float = field(init=False) |
an argument only for __post_init__ |
InitVar[T] |
password: InitVar[str] |
| read-only, hashable instances | @dataclass(frozen=True) |
dict keys, cache keys, settings |
set a field in a frozen __post_init__ |
object.__setattr__(self, name, value) |
|
| sort instances by their fields | @dataclass(order=True) |
fields compared as a tuple, in order |
leave a field out of == and sorting |
field(compare=False) |
a cache, a timestamp |
| hide a secret in the repr | field(repr=False) |
api_key: str = field(repr=False) |
| force keyword arguments | kw_only=True, KW_ONLY, field(kw_only=True) |
Config(debug=True) |
| forbid new attributes and save memory | @dataclass(slots=True) |
typos raise AttributeError |
| copy with changes (also frozen) | dataclasses.replace(obj, **changes) |
replace(cfg, debug=True) |
| convert to a dict or tuple (recursive) | asdict(obj), astuple(obj) |
json.dumps(asdict(order)) |
| list the fields | dataclasses.fields(obj_or_cls) |
[f.name for f in fields(User)] |
| check “is this a dataclass” | dataclasses.is_dataclass(x) |
|
| a tuple with field names | typing.NamedTuple |
lat, lon = point |
| copy a named tuple with a change | nt._replace(field=value) |
|
| a named tuple without type hints (older code) | collections.namedtuple("Point", "x y", defaults=[0]) |
Point(1) → Point(x=1, y=0) |
| type hints for JSON dicts passed on unchanged | TypedDict |
class Payload(TypedDict): id: int |
optional keys in a TypedDict |
NotRequired[T] |
nickname: NotRequired[str] |
| validate and convert untrusted input | a pydantic BaseModel |
User.model_validate(request_json) |
| fixed attributes in a plain class | __slots__ = ("x", "y") |
no __dict__ |
| a quick throwaway object with attributes | types.SimpleNamespace(a=1) |
test doubles, parsed args |
| a read-only view of a dict | types.MappingProxyType(d) |
expose config without copying |
| a fixed set of named options | Enum |
see enums |
Which container?
Section titled “Which container?”| Need | Use | Why |
|---|---|---|
| quick script, keys not known in advance | dict |
no class needed |
| JSON in, JSON out, light processing | dict + TypedDict hints |
stays a dict; mypy checks keys |
| a small result that callers unpack | NamedTuple |
name, score = best |
| a record with defaults, methods, light validation | @dataclass |
standard library, readable, typed |
| a value that must not change, a dict key | @dataclass(frozen=True) or NamedTuple |
hashable |
| millions of small records in memory | @dataclass(slots=True) or NamedTuple |
no per-object __dict__ |
| an object with behavior and changing state | plain class | a client, a service, a model |
| untrusted input (HTTP body, config file, CLI) that must be validated and converted | pydantic BaseModel |
type coercion, clear errors, JSON schema |
| a table of many rows | a pandas or Polars DataFrame | columns, not objects |
dict |
TypedDict |
NamedTuple |
@dataclass |
plain class | pydantic BaseModel |
|
|---|---|---|---|---|---|---|
| Access | d["k"] |
d["k"] |
t.k, t[0] |
o.k |
o.k |
m.k |
| Type hints | no | yes (checker only) | yes | yes | by hand | yes, enforced |
| Run-time validation | no | no | no | __post_init__ by hand |
by hand | yes, automatic |
Converts types ("7" → 7) |
no | no | no | no | by hand | yes (lax mode) |
| Mutable | yes | yes | no | yes (or frozen=True) |
yes | yes (or frozen=True) |
| Hashable | no | no | yes | with frozen=True |
by identity | with frozen=True |
| Unpacks like a tuple | no | no | yes | no | no | no |
| Equals plain data | — | equals a dict | equals a tuple | no | no | no |
__init__, __repr__, __eq__ |
built-in | built-in | generated | generated | by hand | generated |
| To dict / JSON | it is one | it is one | _asdict() |
asdict() |
by hand | model_dump(), model_dump_json() |
| Dependency | none | none | none | none | none | pydantic |
The same record, five ways
Section titled “The same record, five ways”from dataclasses import asdict, dataclassfrom typing import NamedTuple, TypedDict
from pydantic import BaseModel, ValidationError
raw = {"id": "7", "email": "ADA@example.com"} # e.g. a JSON request body
class UserDict(TypedDict): id: int email: str
class UserTuple(NamedTuple): id: int email: str
@dataclassclass UserData: id: int email: str
def __post_init__(self) -> None: self.email = self.email.lower() # normalize by hand
class UserModel(BaseModel): id: int email: str
td: UserDict = {"id": 7, "email": "ada@example.com"} # a plain dict at run timent = UserTuple(7, "ada@example.com")dc = UserData(int(raw["id"]), raw["email"]) # you convert the types yourselfpm = UserModel.model_validate(raw) # pydantic converts "7" -> 7print(type(td).__name__, nt, nt == (7, "ada@example.com"))print(dc, asdict(dc))print(repr(pm), pm.model_dump())print(UserData("7", "x").id == 7) # annotations are not checkedtry: UserModel.model_validate({"id": "seven", "email": "x"})except ValidationError as err: first = err.errors()[0] print(err.error_count(), first["loc"], first["type"])dict UserTuple(id=7, email='ada@example.com') TrueUserData(id=7, email='ada@example.com') {'id': 7, 'email': 'ada@example.com'}UserModel(id=7, email='ADA@example.com') {'id': 7, 'email': 'ADA@example.com'}False1 ('id',) int_parsing@dataclass options
Section titled “@dataclass options”| Parameter | Default | Effect |
|---|---|---|
init |
True |
generate __init__ |
repr |
True |
generate __repr__ (fields with repr=True) |
eq |
True |
generate __eq__: compares fields as a tuple, only with the same class |
order |
False |
generate <, <=, >, >=; needs eq=True |
frozen |
False |
assignment raises FrozenInstanceError; with eq=True, generates __hash__ |
unsafe_hash |
False |
generate __hash__ even when not frozen |
match_args |
True |
generate __match_args__ for case User(name, age): |
kw_only |
False |
every field is keyword-only |
slots |
False |
generate __slots__ (returns a new class) |
weakref_slot |
False |
add a __weakref__ slot (with slots=True) |
| Options | __eq__ |
__hash__ |
Set member / dict key |
|---|---|---|---|
@dataclass |
by fields | None |
no |
frozen=True |
by fields | by fields | yes |
eq=False |
identity | identity | yes, by identity |
unsafe_hash=True |
by fields | by fields | yes, if you never change the fields |
A method you write yourself, such as __repr__, is kept: @dataclass adds only what is missing. With order=True, also writing __lt__ raises TypeError.
field() options
Section titled “field() options”| Argument | Default | Effect |
|---|---|---|
default |
none | the default value |
default_factory |
none | a zero-argument callable called for each new instance: list, dict, lambda: [0] |
init |
True |
a parameter of __init__; False for computed fields |
repr |
True |
shown in __repr__ |
compare |
True |
used by __eq__, the order methods and the hash |
hash |
None |
None follows compare; False leaves it out of the hash |
kw_only |
MISSING |
True: keyword-only parameter |
metadata |
None |
a read-only mapping for your own tools (fields(cls)[0].metadata) |
| Special annotation | Meaning |
|---|---|
x: ClassVar[int] = 0 |
a class attribute, not a field |
x: InitVar[str] |
an __init__ argument passed to __post_init__, not stored |
_: KW_ONLY |
every field below is keyword-only |
no annotation (x = 0) |
a plain class attribute, not a field |
Dataclass recipes
Section titled “Dataclass recipes”import jsonfrom dataclasses import KW_ONLY, asdict, dataclass, field, fields, replace
@dataclassclass Order: id: str items: list[str] = field(default_factory=list) # one list per order price: float = 0.0 total: float = field(init=False) # computed, not an __init__ parameter _: KW_ONLY # everything below is keyword-only currency: str = "USD" note: str = field(default="", repr=False, compare=False)
def __post_init__(self) -> None: # validate and derive after __init__ if self.price < 0: raise ValueError(f"price must be >= 0, got {self.price}") self.total = round(len(self.items) * self.price, 2)
o = Order("A-1", ["pen", "ink"], 2.5, currency="EUR", note="hi")print(o) # note has repr=Falseprint(json.dumps(asdict(o))) # asdict() includes every fieldprint([f.name for f in fields(o)])print(o == Order("A-1", ["pen", "ink"], 2.5, currency="EUR")) # note not comparedo2 = replace(o, price=3.0) # a new object; __post_init__ runs againprint(o2.total, o2.items is o.items) # replace() is shallow: the list is sharedOrder(id='A-1', items=['pen', 'ink'], price=2.5, total=5.0, currency='EUR'){"id": "A-1", "items": ["pen", "ink"], "price": 2.5, "total": 5.0, "currency": "EUR", "note": "hi"}['id', 'items', 'price', 'total', 'currency', 'note']True6.0 Truefrom dataclasses import FrozenInstanceError
@dataclass(frozen=True, order=True, slots=True)class Version: major: int minor: int = 0 label: str = field(default="", compare=False) # not part of ==, < or the hash
v = Version(1, 10, "lts")print([(x.major, x.minor) for x in sorted([Version(2), v, Version(1, 9)])])print(v, v == Version(1, 10))print({v: "supported"}[Version(1, 10)], hasattr(v, "__dict__"))try: v.major = 3except FrozenInstanceError as err: print(type(err).__name__, err)match v: case Version(1, minor): # positional pattern from __match_args__ print("1.x line, minor", minor)[(1, 9), (1, 10), (2, 0)]Version(major=1, minor=10, label='lts') Truesupported FalseFrozenInstanceError cannot assign to field 'major'1.x line, minor 10| Task | Code |
|---|---|
| a required field after defaults | make it keyword-only: field(kw_only=True) or kw_only=True |
| validate types for real | __post_init__ with isinstance, or use pydantic |
| frozen with a derived field | object.__setattr__(self, "slug", ...) in __post_init__ |
| an immutable default in a frozen class | tags: tuple[str, ...] = () |
| inherit from a dataclass | @dataclass class Admin(User): level: int = 1; fields append in order |
| build from a dict | User(**data); unknown keys raise TypeError |
| build from a dict with extra keys | User(**{f.name: data[f.name] for f in fields(User) if f.name in data}) |
| print a long dataclass readably | pprint.pprint(obj) |
| a dataclass in a pydantic model | allowed: pydantic validates standard dataclasses as fields |
NamedTuple and TypedDict in brief
Section titled “NamedTuple and TypedDict in brief”from typing import NamedTuple, NotRequired, TypedDict
class Point(NamedTuple): lat: float lon: float label: str = "" # defaults come last
class Event(TypedDict): name: str user_id: int source: NotRequired[str] # the key may be missing
p = Point(48.86, 2.35, "Paris")lat, lon, _ = p # unpacks like a tupleprint(p.lat, p[1], p._replace(label="FR"))print(p._asdict())e: Event = {"name": "login", "user_id": 7}print(e.get("source", "web"), Point._fields, sorted([Point(2, 0), Point(1, 9)])[0])48.86 2.35 Point(lat=48.86, lon=2.35, label='FR'){'lat': 48.86, 'lon': 2.35, 'label': 'Paris'}web ('lat', 'lon', 'label') Point(lat=1, lon=9, label='')__slots__
Section titled “__slots__”class Plain: def __init__(self, x: float, y: float) -> None: self.x, self.y = x, y
class Slotted: __slots__ = ("x", "y") # fixed attribute names; no __dict__
def __init__(self, x: float, y: float) -> None: self.x, self.y = x, y
s = Slotted(1.0, 2.0)try: s.z = 3.0 # a typo or a new attributeexcept AttributeError as err: print(type(err).__name__, "for 'z'") # the message text differs by versionprint(hasattr(Plain(1, 2), "__dict__"), hasattr(s, "__dict__"))print(vars(Plain(1, 2)), Slotted.__slots__)AttributeError for 'z'True False{'x': 1, 'y': 2} ('x', 'y')| Rule | Detail |
|---|---|
| saves | the per-object __dict__; measure with tracemalloc before you optimize |
| forbids | new attributes and vars(obj) |
| unset slot | reading it raises AttributeError |
| class attribute with a slot’s name | ValueError: 'x' in __slots__ conflicts with class variable |
subclass without __slots__ |
gets a __dict__ again |
subclass with __slots__ |
lists only its new names |
| multiple inheritance | at most one base may have non-empty slots |
cached_property |
needs a __dict__: fails on slotted classes |
@dataclass(slots=True) |
handles defaults for you; zero-argument super() in its methods fails on 3.12–3.13 |
| does not freeze values | combine with frozen=True for that |
Gotchas
Section titled “Gotchas”- Mutable default. Symptom:
items: list = []raisesValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. Fix:field(default_factory=list). - Field order. Symptom:
TypeError: non-default argument 'b' follows default argument 'a'. Fix: put required fields first, or make later fields keyword-only. - Annotations are not checked. Symptom:
User(id="7")stores a string. Fix: convert in__post_init__, or use pydantic for untrusted input. - No annotation, no field. Symptom:
x = 0in a dataclass is missing from__init__andasdict(). Fix: annotate it:x: int = 0. __post_init__runs once. Symptom: later assignments skip the validation. Fix: usefrozen=True, or a property or descriptor for that field.frozen=Trueis shallow. Symptom: a list field still changes, andhash()fails because lists are unhashable. Fix: store tuples and frozensets.replace()shares mutable fields. Symptom: changing the copy’s list changes the original. Fix: pass a new list:replace(o, items=list(o.items)).asdict()deep-copies and keeps enum members. Symptom: slow on big nested objects;json.dumps()fails for a plainEnum. Fix: useStrEnumor convert.value; write a customto_dict()for hot paths.compare=Falsealso removes the field from the hash. Symptom: two objects with different labels are equal. Fix: that is intended; keep identity fields compared.order=Truesorts by field order. Symptom: records sort by the first field, not the one you meant. Fix: put the sort key first, or usesorted(key=...).NamedTupleequals a plain tuple. Symptom:Point(1, 2) == (1, 2)isTrue, and two different named tuples with the same values are equal. Fix: use a frozen dataclass when the type matters.TypedDictis only for the type checker. Symptom: missing or wrong keys pass at run time. Fix: validate with pydantic’sTypeAdapteror by hand.dicteverywhere. Symptom:KeyError: 'emial'deep in the code. Fix: turn the record into a dataclass at the boundary.__slots__with a class-level default. Symptom:ValueError: ... conflicts with class variable. Fix: set defaults in__init__, or use@dataclass(slots=True).
Learn more
Section titled “Learn more”- Lesson: Dataclasses, enums and slots and its cheat sheet
TypedDictandNamedTuplehints: Type hints cheat sheet- Related: Classes, Enums, Dunder methods