7/29
Part 2 of 6 · Data model and one pathLearn and do

Turn each level into a data model

Spend the first two minutes of every level reading, not typing. Then write what you read as a comment at the top of the class.

This part shows each idea on the task manager first, one of the other systems the test hands out. It's small, which makes the ideas easy to see: each task has a name, a command and sometimes a deadline, and the code calls it the scheduler. Each idea then lands in your database, and in the full problem at the end. Here's the scheduler's data model, at the level where deadlines arrive:

# name -> Task(command, deadline)
#     a deadline of None never expires
# schedule(name, command, deadline=None)
#     replaces any task with that name, deadline and all
# status(name, now) -> command, or None
#     None once now >= deadline
# cancel(name, now) -> True if a live task was removed
# pending(now) -> live names, sorted

That comment is a data model: what you store, under which key, and what each call gives back. It describes one dict:

self._tasks: nameTask
backupcommand tar, deadline 100
reportcommand make, deadline None

Five questions fill in the model

  1. What is the key, and what does each record hold besides its value?
  2. What comes back when something is missing: None, False, an empty list, an error?
  3. What order do lists come back in, and how are ties broken?
  4. What happens on a repeat write: replace, reject or merge?
  5. Which comparisons sit on a boundary, and is each one inclusive or exclusive?

Store a record, not a bare value

LevelWhat backup holdsWhen deadlines arrive
1, a bare valuetara deadline has nowhere to go
3, a recordTask(tar, 100)a new field is one more line

Say the scheduler's level 1 has no deadlines. Then self._tasks[name] = command passes every test. When deadlines arrive, every line that touches self._tasks has to change at once, with the timer running.

A record is one small object that holds everything about one entry. A record type costs a few lines up front:

from dataclasses import dataclass


@dataclass(frozen=True)
class Task:
    command: str
    # None: no deadline
    deadline: int | None = None


print(Task("tar"))
print(Task("tar", 100))
Predict

Task is a frozen dataclass whose deadline defaults to None. What does print(Task("tar")) show?

Pick one to see what it prints.
Pick an answer above to see the rest