Dataclasses
@dataclass writes __init__, __repr__ and __eq__ from a list of annotated fields. Use it for objects that mainly hold data.
from dataclasses import dataclass, field
@dataclass
class Order:
item: str
qty: int = 1
notes: list[str] = field(
default_factory=list)Each Order gets its own notes list. A plain notes: list = [] is rejected with an error, because all instances would share one list.
Options
frozen=Truemakes instances immutable and hashable, so they can be dict keys.order=Trueadds<,>and friends, comparing fields in order.slots=Trueuses less memory and blocks stray attributes.
Validation
__post_init__ runs right after the generated __init__:
@dataclass
class Age:
years: int
def __post_init__(self):
if self.years < 0:
raise ValueError("negative")Your task
Write a dataclass Task with title: str, priority: int = 0 and tags: list[str] defaulting to a new empty list, raising ValueError for an empty title. Write a frozen dataclass Point with x: int and y: int.
The explanation opens here once every check passes.