Explain it simply
Explain it simply
A hospital does not track patients as "the person in bed three"; it uses a patient number. When someone is discharged and beds are shuffled, bed three may hold a different person, but the patient number never changes. In this to-do app every task gets an id like that.
The app is split into three parts: the rules for handling tasks (domain), saving and loading them from a file (storage), and showing them on screen (presentation). Changing one part never forces you to touch the others.
Problem → Why → Solution
The problem: "delete 2" deletes the wrong task
Picture a simple app that stores tasks as a list of strings in tasks.txt and numbers them with enumerate(tasks, 1). The user looks at the list and decides to delete number 2. If another command removes task 1 in between, every number shifts by one and "2" is no longer the task the user saw.
Sorting the list alphabetically for display causes the same problem. A list of strings also has nowhere to store whether a task is done. And if save_tasks() overwrites the file directly, a program that dies mid-write leaves only half the file behind and tasks are lost.
tasks = ["Buy milk", "Call Mya", "Pay rent"]
# The user sees: 1. Buy milk 2. Call Mya 3. Pay rent
# and wants to delete "Call Mya" by typing 2 ...
tasks.pop(0) # ... but another command removed task 1 first
tasks.pop(2 - 1) # deletes "Pay rent", not "Call Mya"
print(tasks) # ['Call Mya']Why does this happen?
A list position is not an item's identity; it only says where the item sits right now, and it changes with every insert, delete or sort. Anything that refers to a task later, whether a command, a URL or a database row, needs an id that never changes. The id counter (next_id) must be saved too, or a reload will reuse the id of a deleted task.
Core concept: domain, storage and presentation
Even in a small app, change becomes easy when the questions "what do we store?", "which changes are allowed?", "where is it kept?" and "how is it shown?" are answered in separate places in the code. This project is organised like this.
| Layer | In this project | Must not know about |
|---|---|---|
| Domain | Todo, TodoList, TodoError | Files, JSON, print(), input() |
| Storage | save(), load() | How tasks are displayed |
| Presentation | show(), later a CLI or GUI | Where the data is stored |
1. Model the state explicitly
@dataclass Todo has three fields: id, text and done. The dataclass writes __init__ and __repr__ for you, and asdict() turns it into a dict that is easy to save as JSON. Adding a field later, such as due_date, is far easier than with a bare string.
2. Give every change its own method
add(), toggle() and delete() are the only ways the state can change. add() rejects empty text and takes the id from next_id; toggle() and delete() locate the task with find() and raise TodoError when the id does not exist. Because the rules live in one place, a CLI and a web front end obey them identically.
3. Keep storage outside, as an adapter
save() and load() only translate a TodoList to and from JSON. They store next_id as well, so after a reload numbering continues at 4 and the deleted id 2 is never reused. Switching to SQLite later means rewriting just these two functions.
4. Save atomically
Opening the real file in "w" mode empties it immediately, so a crash mid-write loses data. Instead the code writes todos.json.tmp first and then renames it with os.replace(). On the same filesystem os.replace() is atomic: anyone reading sees either the old file or the new one, never a half-written file.
- load() turns the file into a TodoList
- Methods change tasks by id
- save() writes a temp file, replaces
- show() prints the current state
The number shown to the user must be the id, never the list index; that is what keeps commands correct after any sort.
General pattern
@dataclass
class Item:
id: int
... # the fields you need
class Store: # domain: rules + stable ids
def add(self, ...) -> Item: ...
def change(self, item_id: int, ...) -> Item: ...
def save(store, path): ... # write tmp, then os.replace()
def load(path) -> Store: ... # missing file -> empty StoreA dataclass defines the shape, a domain class owns ids and rules, and separate save and load functions own storage.
Example: model, storage and a reload check
The demo uses two sample tasks, "Learn Python" and "Build To-Do App", and the app is built in three layers. The demo runs inside tempfile.TemporaryDirectory(), so no tasks.txt is left in your folder and an old file can never change the result between runs. It saves, reloads and checks that ids, done status and next_id all survive.
import json
import os
import tempfile
from dataclasses import asdict, dataclass
# ===== 1. Domain model: stable ids, not list positions =====
class TodoError(Exception):
"""A request the to-do list cannot carry out."""
@dataclass
class Todo:
id: int
text: str
done: bool = False
class TodoList:
def __init__(self, todos: list[Todo] | None = None, next_id: int = 1):
self.todos = todos or []
self.next_id = next_id
def add(self, text: str) -> Todo:
text = text.strip()
if not text:
raise TodoError("a task needs some text")
todo = Todo(self.next_id, text)
self.next_id += 1
self.todos.append(todo)
return todo
def find(self, todo_id: int) -> Todo:
for todo in self.todos:
if todo.id == todo_id:
return todo
raise TodoError(f"no task with id {todo_id}")
def toggle(self, todo_id: int) -> Todo:
todo = self.find(todo_id)
todo.done = not todo.done
return todo
def delete(self, todo_id: int) -> Todo:
todo = self.find(todo_id)
self.todos.remove(todo)
return todo
def pending(self) -> list[Todo]:
return [t for t in self.todos if not t.done]
# ===== 2. Storage adapter: JSON file with an atomic save =====
def save(todo_list: TodoList, path: str) -> None:
data = {"next_id": todo_list.next_id,
"todos": [asdict(t) for t in todo_list.todos]}
tmp_path = path + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
os.replace(tmp_path, path) # readers see the old file or the new one
def load(path: str) -> TodoList:
if not os.path.exists(path):
return TodoList()
with open(path, encoding="utf-8") as f:
data = json.load(f)
return TodoList([Todo(**t) for t in data["todos"]], data["next_id"])
# ===== 3. Presentation =====
def show(todo_list: TodoList) -> None:
for t in todo_list.todos:
print(f" [{'x' if t.done else ' '}] #{t.id} {t.text}")
# ===== 4. Demo in a throwaway folder (no input() needed) =====
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "todos.json")
todos = load(path) # no file yet -> empty list
todos.add("Learn Python")
todos.add("Build To-Do App")
todos.add("Write tests")
todos.toggle(1)
todos.delete(2)
save(todos, path)
reloaded = load(path)
print("After reload:")
show(reloaded)
print(f"Pending: {[t.text for t in reloaded.pending()]}")
print(f"New task gets id {reloaded.add('Deploy').id}")
try:
reloaded.toggle(2)
except TodoError as error:
print(f"Error: {error}")Code breakdown
- Data shape as a dataclass
done: bool = FalseBecause the field has a default, Todo(1, "Learn Python") starts with done set to False. Fields with defaults must come after fields without them.
- Ids come from a counter
self.next_id += 1The id is not len(self.todos) + 1, which would repeat after a delete shrinks the list. The counter only ever goes up.
- Lookup by id, not index
raise TodoError(f"no task with id {todo_id}")find() searches for the matching id and, if none exists, raises a domain error instead of a vague IndexError. The demo's last line shows this error for the deleted id 2.
- Atomic replace
os.replace(tmp_path, path) # readers see the old file or the new oneThe temp file is fully written before the rename, so a crash mid-write leaves the old todos.json intact. It overwrites an existing file on Windows too.
- Rebuild objects on load
return TodoList([Todo(**t) for t in data["todos"]], data["next_id"])JSON gives back dicts, and Todo(**t) passes their keys as keyword arguments. next_id is restored as well, which is why "Deploy" gets id 4 after the reload rather than a reused 3.
After reload:
[x] #1 Learn Python
[ ] #3 Write tests
Pending: ['Write tests']
New task gets id 4
Error: no task with id 2Corrupted files and concurrent writes
If a user edits todos.json by hand and leaves a stray comma, json.load() raises json.JSONDecodeError. The app should neither crash nor overwrite the file with an empty list and destroy the data. A good policy is to catch the error, rename the file to todos.json.broken and tell the user.
If two terminals run the app at once, both load the file, apply their own change and save. Whoever saves last wipes out the other's change, a lost update. That may be acceptable for a personal JSON file; for several users, move to a database with transactions such as SQLite.
Test the domain without storage
TodoList knows nothing about files, so a test such as todos = TodoList(); todos.add("x"); assert todos.find(1).text == "x" never touches the disk and finishes in milliseconds. Run storage tests in a temporary directory, as the demo does.
In real projects
In real projects
A to-do app is a teaching project, but the same structure runs issue trackers, shopping carts, note apps and booking systems. Every record has a stable id, and URLs (/tasks/42), API requests and database foreign keys all point at that id. Production systems often use UUIDs instead of an integer counter, because two devices working offline can then create records without their ids colliding.
Teams cover the domain functions with unit tests and storage with integration tests in a temporary directory. Typical cases: data survives a reload, two tasks with the same text are allowed because their ids differ, deleting a missing id fails cleanly, and a failed save leaves the old file intact.
Common mistakes
Common mistakes
Computing the id as len(list) + 1
Delete #2 out of three tasks and add a new one: len + 1 gives 3, duplicating the existing #3, and "delete 3" becomes ambiguous. Use a next_id counter and save it with the data.
Calling save() or print() inside domain methods
Writing the file inside add() makes every test touch the disk, and importing a hundred tasks writes the file a hundred times. A print() there leaks terminal output into a GUI version. Methods should change state and return a result; the caller decides when to save and what to display.
Overwriting the file after a failed load
With except Exception: return TodoList(), a corrupted JSON file makes the app start empty, and the next save erases every task the user had. Handle "file missing" (first run) and "file broken" as different cases.
Mini challenge
Write the command handler
Write handle(), which takes one text command, updates a TodoList and returns the message to display. Without calling input(), test it by looping over a list of commands.
- Support add <text>, done <id>, del <id>, list and clear-done
- Raise TodoError for a non-numeric id ("two") and for a missing id (9)
- clear-done reports how many finished tasks it removed
- Unknown commands raise TodoError; the loop prints the message and keeps going
# Paste Todo, TodoList (with add and find) and TodoError from the lesson here.
def parse_id(arg: str) -> int:
# TODO: digits only -> int, otherwise TodoError("'two' is not a task id")
...
def handle(todos: "TodoList", line: str) -> str:
"""Run one command and return the message to show."""
command, _, arg = line.strip().partition(" ")
# TODO: add <text> -> "Added #1: Buy milk"
# TODO: done <id> -> "Completed #1"
# TODO: del <id> -> "Deleted #1"
# TODO: list -> one "[x] #1 text" line per task, or "(no tasks)"
# TODO: clear-done -> "Removed 1 finished task(s)"
# TODO: anything else -> raise TodoError
...
commands = ["add Buy milk", "add Call Mya", "add", "done 1", "del two",
"del 9", "add Pay rent", "list", "clear-done", "list", "undo"]
# TODO: run each command, print "> command" and then the result or "Error: ..."Expected: Tasks #1 and #2 are added, then three errors appear for the empty add, "two" and id 9. The first list shows [x] #1, clear-done reports one removed task, the second list shows only #2 and #3, and undo is an unknown command.
Show hint
str.partition(" ") splits once, at the first space, so "add Buy milk" gives the command "add" and the arg "Buy milk". Check ids with arg.isdigit().
Show solution
from dataclasses import dataclass
class TodoError(Exception):
pass
@dataclass
class Todo:
id: int
text: str
done: bool = False
class TodoList:
def __init__(self) -> None:
self.todos: list[Todo] = []
self.next_id = 1
def add(self, text: str) -> Todo:
if not text.strip():
raise TodoError("a task needs some text")
todo = Todo(self.next_id, text.strip())
self.next_id += 1
self.todos.append(todo)
return todo
def find(self, todo_id: int) -> Todo:
for todo in self.todos:
if todo.id == todo_id:
return todo
raise TodoError(f"no task with id {todo_id}")
def parse_id(arg: str) -> int:
if not arg.isdigit():
raise TodoError(f"'{arg}' is not a task id")
return int(arg)
def handle(todos: TodoList, line: str) -> str:
"""Run one command and return the message to show."""
command, _, arg = line.strip().partition(" ")
if command == "add":
todo = todos.add(arg)
return f"Added #{todo.id}: {todo.text}"
if command == "done":
todo = todos.find(parse_id(arg))
todo.done = True
return f"Completed #{todo.id}"
if command == "del":
todo = todos.find(parse_id(arg))
todos.todos.remove(todo)
return f"Deleted #{todo.id}"
if command == "list":
rows = [f"[{'x' if t.done else ' '}] #{t.id} {t.text}" for t in todos.todos]
return "\n".join(rows) or "(no tasks)"
if command == "clear-done":
before = len(todos.todos)
todos.todos = [t for t in todos.todos if not t.done]
return f"Removed {before - len(todos.todos)} finished task(s)"
raise TodoError(f"unknown command '{command}'")
commands = ["add Buy milk", "add Call Mya", "add", "done 1", "del two",
"del 9", "add Pay rent", "list", "clear-done", "list", "undo"]
todos = TodoList()
for line in commands:
print(f"> {line}")
try:
print(handle(todos, line))
except TodoError as error:
print(f"Error: {error}")Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Refer to tasks by stable ids, never list positions, and save next_id with the data
- Define the shape with @dataclass and give every state change its own domain method
- Keep storage in save() and load() adapters, and save atomically with a temp file plus os.replace()
- The domain must not know about input(), print() or files, so it can be tested without a keyboard or disk
The Python Tutorial — Python Software Foundation