Classes and objects
Project: validated study sessions
Combine dataclasses, validation, and a plan total.
Lesson 53 of 63
Reading: about 2 min
Lesson + practice: about 20 min
Difficulty: Intermediate
On this page5 sections
Build a session record that checks its fields when created, then store several records in a plan. Keep totals as calculations from the current records.
Worked example
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Session:
subject: str
minutes: int
def __post_init__(self):
if not isinstance(self.subject, str) or not self.subject.strip() or type(self.minutes) is not int or self.minutes <= 0:
raise ValueError("invalid session")
@dataclass
class Plan:
sessions: list[Session] = field(default_factory=list)
def total(self):
return sum(item.minutes for item in self.sessions)
plan = Plan([Session("Python", 20), Session("SQL", 25)])
print(plan.total())45
Why this works
__post_init__ runs after the dataclass-generated initializer. frozen=True prevents ordinary reassignment of a validated session’s fields. default_factory creates a fresh list for each Plan instance.
Another case
from dataclasses import dataclass
@dataclass(frozen=True)
class StudySession:
subject: str
minutes: int
def __post_init__(self):
if type(self.minutes) is not int or self.minutes <= 0:
raise ValueError("invalid session")
try:
StudySession("Python", 0)
except ValueError as error:
print(error)invalid session
Practice
Try Session(" ", 20), Session("Python", True), and a valid Session("Python", 1).
Check the practice result
Reveal answer
The first two raise ValueError; the third is valid.
Try another case
After session = Session("Python", 20), what happens if you run session.minutes = 30?
Check your answer
Reveal answer
It raises dataclasses.FrozenInstanceError, so a validated value cannot be reassigned.
Your progress
Reveal the check answer or reach the end to complete this lesson.