Browse topics

Data classes

Version
3.14
Since
3.7
Review
Draft

Summary#

@dataclass generates methods such as __init__, __repr__ and __eq__ from annotated class fields. Options add ordering or block attribute assignment.

Syntax#

python
@dataclass(frozen=True, order=True)
class Item:
    name: str
    tags: list[str] = field(default_factory=list)

Example#

python
from dataclasses import FrozenInstanceError, asdict, dataclass, field


@dataclass(frozen=True, order=True)
class Release:
    major: int
    minor: int
    tags: list[str] = field(default_factory=list, compare=False)


first = Release(1, 2)
second = Release(1, 10, ["lts"])
print(first)
print(first < second)
print(asdict(second))

try:
    first.major = 2
except FrozenInstanceError as error:
    print(error)

first.tags.append("local")
print(first.tags, Release(1, 3).tags)

Expected output#

Text
Release(major=1, minor=2, tags=[])
True
{'major': 1, 'minor': 10, 'tags': ['lts']}
cannot assign to field 'major'
['local'] []

Common mistakes#

A default such as tags: list[str] = [] raises ValueError. Use field(default_factory=list) to give each instance its own list. frozen=True blocks ordinary attribute assignment and deletion. A list stored in a frozen instance can still be changed. Annotations are not type checks at runtime.

Version applicability#

The dataclasses module was added in Python 3.7. The annotated list[str] in both snippets requires Python 3.9 or later as written. The slots and kw_only options require Python 3.10 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0