Data classes
A data class describes a record with named fields. Python can generate its initializer, representation, and value-based equality from those fields. This is useful for structured records such as tickets, coordinates, or line items.
On this page
Model a record
from dataclasses import dataclass, field
@dataclass
class Ticket:
title: str
labels: list[str] = field(default_factory=list)
bug = Ticket("Fix the export")
bug.labels.append("urgent")
other = Ticket("Write a guide")
print(bug.labels, other.labels)The decorator @dataclass processes the class definition. Calling Ticket with a title fills the first field. The factory constructs a fresh list for each ticket, so the output is ['urgent'] []. Type annotations describe the intended field types; callers can still supply other values at runtime.
Decide what equality means
Two tickets with the same field values compare equal by default. This helps compare the results of a calculation in a test. If a record needs a stable identity across edits, store a separate identifier and compare that identifier when selecting the record.