Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Objects with purpose
EXPERIMENT 48 / 101

A backlog with boundaries.

Combine dataclasses, validation, and composition into a small testable system.

ADVANCED LAB / BUILD PROJECT
BY NAVAN SAMI◷ 12 MIN READPYTHON 3

01 The idea

A useful object design keeps decisions in the domain and storage behind a narrow boundary. This build represents a task as a dataclass, validates its duration during construction, and injects a repository into a service. The service can calculate a report without knowing how the repository might later use JSON or a database.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

oop_project.py
from dataclasses import dataclass
@dataclass(frozen=True)
class Task:
    name: str
    minutes: int
    def __post_init__(self):
        if not self.name.strip() or type(self.minutes) is not int or self.minutes < 0:
            raise ValueError("A task needs a name and nonnegative integer minutes")
class MemoryTasks:
    def __init__(self): self._items = []
    def add(self, task): self._items.append(task)
    def all(self): return tuple(self._items)
class ReportService:
    def __init__(self, repository): self.repository = repository
    def total_minutes(self): return sum(t.minutes for t in self.repository.all())
repository = MemoryTasks()
repository.add(Task("Build", 40))
repository.add(Task("Test", 20))
print(ReportService(repository).total_minutes())
↳ EXPECTED OUTPUT
60

03 Under the hood

  1. 1

    __post_init__ checks the contract after generated initialization. Frozen attributes make these particular records harder to change accidentally.

  2. 2

    all() returns a tuple so callers do not receive the repository’s mutable list. This controls list membership; it would not deeply freeze mutable task objects.

  3. 3

    The service depends on repository behaviour. Add a persistent implementation later and run the same service tests against it, plus separate integration tests for the storage adapter.

04 Your turn, builder

A SMALL MISSION

Extend the repository with find_by_name(name), returning None when no task matches.

Reveal one possible solution +
one_possible_solution.py
from dataclasses import dataclass
@dataclass
class Task:
    name: str
    minutes: int
class Repository:
    def __init__(self, items): self.items = list(items)
    def find_by_name(self, name):
        return next((task for task in self.items if task.name == name), None)
repository = Repository([Task("Build", 40)])
print(repository.find_by_name("Build").minutes)
print(repository.find_by_name("Missing"))

↗ Definition of done

  • □Reject blank names and negative durations.
  • □Return a stable total for an empty and a populated repository.
  • □Test the service with an in-memory repository.
  • □Add a lookup method and test missing records.

05 Check your signal

QUICK SIGNAL CHECK

Which layer should know the database driver details?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.