12/29
Part 2 of 6 · Data model and one pathLearn and do
Put the rule in one helper
Write the rule once, in a private helper, and send every method through it:
class Scheduler:
def __init__(self) -> None:
self._tasks: dict[str, Task] = {}
def schedule(self, name: str, command: str, deadline: int | None = None) -> None:
self._tasks[name] = Task(command, deadline)
def _live(self, name: str, now: int) -> Task | None:
"""The task if it's live at now, else None."""
task = self._tasks.get(name)
if task is None or (task.deadline is not None and now >= task.deadline):
return None
return task
def status(self, name: str, now: int) -> str | None:
task = self._live(name, now)
return task.command if task else None
def cancel(self, name: str, now: int) -> bool:
if self._live(name, now) is None:
return False
del self._tasks[name]
return True
def pending(self, now: int) -> list[str]:
return sorted(name for name in self._tasks if self._live(name, now))
scheduler = Scheduler()
scheduler.schedule("backup", "tar", deadline=100)
print(scheduler.status("backup", 100))
print(scheduler.pending(100))
print(scheduler.cancel("backup", 100))
Now every method reads through one _live helper. Same task, same moment. What do the three say?
Pick one to see what it prints.
Pick an answer above to see the rest
A new level wants _live to act differently for one caller. What do you do?
Pick an answer above to see the rest
backup is due at 100. Then it's scheduled again with no deadline, and the code changes the old record's command in place. Is it live at 150?
Pick an answer above to see the rest