Dataclass
PronunciationDAY-tuh-klas
Definition
A dataclass is a class meant mainly to hold data. The @dataclass decorator writes __init__, __repr__ and __eq__ for you from the field list.
Where you hear it
In modern Python code, code reviews that remove boilerplate, and explanations of records and value objects.
Examples
Use a dataclass for the member record instead of writing the constructor by hand.
A frozen dataclass cannot be changed after creation.
The Address dataclass gives us equality and a readable repr without extra code.
Common mistake
Using a mutable default like tags: list = []. Use field(default_factory=list) so each object gets its own list.
Don't confuse with
A TypedDict, which only describes the shape of a dictionary. A dataclass creates real objects.
Say it at work
- In a meeting or chat
Make it a dataclass; we don't need a hand-written constructor.
- In an email or ticket
Freeze the dataclass so it can be used as a dictionary key.
Keep exploring
More in Programming Fundamentals