Python Projects · Lesson 145 of 149

Python Project To-do List in a File

What you will build

  • A to-do list that keeps its tasks between runs, in a JSON file
  • A dataclass (Task) and a class (TodoList)
  • A command loop (add, list, done, remove, clear, quit)
  • Safe saving, error handling and tests

1. The idea

The first project forgot everything when it ended. A real tool must remember. This one keeps tasks in a file so that tomorrow's session sees today's list:

> add buy milk
added 1: buy milk
> list
  1. [ ] buy milk

2. The design

Piece Job
Task (dataclass, lesson 13.11) one task: id, title, done
TodoList (class) holds the tasks, loads and saves the file, and offers add, complete, remove, clear_done
lines() the list as lines of text (no printing inside the class)
run_command(todo, line) understands one typed command, returns the text to show
main() the loop that reads commands with input

Three design choices to notice:

  1. Storage format: JSON (lesson 15.7): a list of objects, easy to read, edit and extend. A dataclass converts to and from dictionaries (asdict, Task(**item)).
  2. Logic apart from interface: TodoList never prints or asks; run_command returns text. So everything can be tested (as in lesson 21.1).
  3. Safe saving: write to a temporary file and then replace the real one, so a crash cannot leave a half-written file (lesson 15.2).

3. The code

todo.py:

"""To-do list that is saved in a JSON file."""

import json
from dataclasses import asdict, dataclass
from pathlib import Path


@dataclass
class Task:
    id: int
    title: str
    done: bool = False


class TodoList:
    def __init__(self, path):
        self.path = Path(path)
        self.tasks = self._load()

    def _load(self):
        try:
            data = json.loads(self.path.read_text(encoding="utf-8"))
        except FileNotFoundError:
            return []
        except json.JSONDecodeError:
            raise ValueError(f"{self.path} is damaged; fix or delete it") from None
        return [Task(**item) for item in data]

    def save(self):
        text = json.dumps([asdict(t) for t in self.tasks], indent=2, ensure_ascii=False)
        temp = self.path.with_suffix(".tmp")
        temp.write_text(text + "\n", encoding="utf-8")
        temp.replace(self.path)               # replace the file in one step

    def _next_id(self):
        return max((t.id for t in self.tasks), default=0) + 1

    def add(self, title):
        title = title.strip()
        if not title:
            raise ValueError("a task needs a title")
        task = Task(self._next_id(), title)
        self.tasks.append(task)
        self.save()
        return task

    def find(self, task_id):
        for task in self.tasks:
            if task.id == task_id:
                return task
        raise KeyError(f"no task with id {task_id}")

    def complete(self, task_id):
        self.find(task_id).done = True
        self.save()

    def remove(self, task_id):
        self.tasks.remove(self.find(task_id))
        self.save()

    def clear_done(self):
        before = len(self.tasks)
        self.tasks = [t for t in self.tasks if not t.done]
        self.save()
        return before - len(self.tasks)

    def lines(self, show_done=True):
        shown = [t for t in self.tasks if show_done or not t.done]
        if not shown:
            return ["(nothing to do)"]
        return [f"{t.id:>3}. [{'x' if t.done else ' '}] {t.title}" for t in shown]


HELP = "commands: add <title> | list | done <id> | remove <id> | clear | quit"


def parse_id(text):
    try:
        return int(text)
    except ValueError:
        raise ValueError(f"'{text.strip()}' is not a task number") from None


def run_command(todo, line):
    """Carry out one command and return the text to show. Returns None to quit."""
    command, _, argument = line.strip().partition(" ")
    command = command.lower()
    try:
        if command == "add":
            task = todo.add(argument)
            return f"added {task.id}: {task.title}"
        if command == "list":
            return "\n".join(todo.lines())
        if command == "done":
            todo.complete(parse_id(argument))
            return f"task {argument} marked done"
        if command == "remove":
            todo.remove(parse_id(argument))
            return f"task {argument} removed"
        if command == "clear":
            return f"cleared {todo.clear_done()} finished task(s)"
        if command in ("quit", "exit"):
            return None
        return HELP
    except (ValueError, KeyError) as error:
        return f"error: {error.args[0]}"


def main(path="todo.json"):
    todo = TodoList(path)
    print(HELP)
    while True:
        reply = run_command(todo, input("> "))
        if reply is None:
            break
        print(reply)


if __name__ == "__main__":
    main()

Some details worth understanding:

  • Loading: a missing file simply means an empty list (the first run). A file that is not valid JSON raises a clear ValueError instead of crashing with a JSON traceback.
  • IDs: max(..., default=0) + 1 gives the next free number, and works on an empty list. IDs are never shown twice in one list. (After removing the highest task, its number can be reused; the tests cover this.)
  • find raises KeyError for an unknown id, a natural choice for a missing key (lesson 14.4).
  • clear_done rebuilds the list with a comprehension (lesson 12.1) and returns how many tasks it dropped.
  • partition(" ") splits "add buy milk" into the command add and the rest buy milk, which is exactly what is needed (lesson 4.4).
  • run_command catches the two error types the logic can raise and turns them into error: ... text. error.args[0] is the message (a KeyError would show extra quotes with str(error)).
Quick check: why does `save` write to `todo.tmp` first and then call `replace`?

If the program crashes while writing, the old todo.json is still intact; the replacement happens in one step.

4. A demo run

This script drives the list with prepared commands (in a temporary folder, so nothing is left behind):

import tempfile
from pathlib import Path

from todo import TodoList, run_command

with tempfile.TemporaryDirectory() as folder:
    path = Path(folder) / "todo.json"
    todo = TodoList(path)
    for line in ["list", "add buy milk", "add call Rina", "add  ", "add pay bills",
                 "done 2", "done 9", "done x", "list", "remove 1", "dance", "clear", "list"]:
        print(f"> {line}")
        print(run_command(todo, line))

    print("--- the file on disk")
    print(path.read_text(encoding="utf-8"), end="")

    print("--- a new session reads the same file")
    again = TodoList(path)
    print("\n".join(again.lines()))
    print("next id:", again.add("water plants").id)

    print("--- a damaged file")
    path.write_text("{not json", encoding="utf-8")
    try:
        TodoList(path)
    except ValueError as error:
        print("ValueError:", str(error).replace(folder, "<folder>").replace(chr(92), "/"))

Output:

> list
(nothing to do)
> add buy milk
added 1: buy milk
> add call Rina
added 2: call Rina
> add  
error: a task needs a title
> add pay bills
added 3: pay bills
> done 2
task 2 marked done
> done 9
error: no task with id 9
> done x
error: 'x' is not a task number
> list
  1. [ ] buy milk
  2. [x] call Rina
  3. [ ] pay bills
> remove 1
task 1 removed
> dance
commands: add <title> | list | done <id> | remove <id> | clear | quit
> clear
cleared 1 finished task(s)
> list
  3. [ ] pay bills
--- the file on disk
[
  {
    "id": 3,
    "title": "pay bills",
    "done": false
  }
]
--- a new session reads the same file
  3. [ ] pay bills
next id: 4
--- a damaged file
ValueError: <folder>/todo.json is damaged; fix or delete it

Every error case is handled with a message, the data survives a "restart" (a second TodoList reading the same file), and the damaged file produces a readable error. The task names are made up.

5. Tests

test_todo.py checks the behaviour with a fresh temporary file per test (setUp and tearDown, lesson 18.2):

import tempfile
import unittest
from pathlib import Path

from todo import TodoList, run_command


class TodoTests(unittest.TestCase):
    def setUp(self):
        self.folder = tempfile.TemporaryDirectory()
        self.path = Path(self.folder.name) / "todo.json"
        self.todo = TodoList(self.path)

    def tearDown(self):
        self.folder.cleanup()

    def test_add_and_ids_keep_growing(self):
        self.todo.add("one")
        self.todo.add("two")
        self.todo.remove(2)
        self.assertEqual(self.todo.add("three").id, 2)
        self.todo.add("four")
        self.assertEqual([t.id for t in self.todo.tasks], [1, 2, 3])

    def test_blank_title_is_rejected(self):
        with self.assertRaises(ValueError):
            self.todo.add("   ")

    def test_data_survives_a_restart(self):
        self.todo.add("keep me")
        self.todo.complete(1)
        again = TodoList(self.path)
        self.assertEqual(again.tasks[0].title, "keep me")
        self.assertTrue(again.tasks[0].done)

    def test_clear_removes_only_finished(self):
        self.todo.add("a")
        self.todo.add("b")
        self.todo.complete(1)
        self.assertEqual(self.todo.clear_done(), 1)
        self.assertEqual([t.title for t in self.todo.tasks], ["b"])

    def test_unknown_id(self):
        with self.assertRaises(KeyError):
            self.todo.complete(99)

    def test_damaged_file(self):
        self.path.write_text("{oops", encoding="utf-8")
        with self.assertRaises(ValueError):
            TodoList(self.path)

    def test_commands(self):
        self.assertEqual(run_command(self.todo, "add milk"), "added 1: milk")
        self.assertIn("[ ] milk", run_command(self.todo, "list"))
        self.assertEqual(run_command(self.todo, "done x"), "error: 'x' is not a task number")
        self.assertEqual(run_command(self.todo, "done 5"), "error: no task with id 5")
        self.assertIsNone(run_command(self.todo, "quit"))
        self.assertTrue(run_command(self.todo, "nonsense").startswith("commands:"))


if __name__ == "__main__":
    unittest.main()

Result: Ran 7 tests ... OK. To use the real program, run python todo.py; it creates todo.json in the current folder.

6. Ideas to extend it

  1. Due dates: add a due field (ISO text, lesson 17.1) and a list overdue command.
  2. Priorities and sorting (lesson 7.4): high, normal, low.
  3. Editing: an edit <id> <new title> command.
  4. Search: find <word> using a comprehension.
  5. Undo: keep the previous list in memory and restore it.
  6. Command-line arguments instead of a loop: python todo.py add "buy milk" with argparse (the next-but-two project does this for another tool).
  7. Another storage: swap JSON for SQLite (lesson 17.10), keeping the TodoList methods the same, so run_command and the tests do not change.

Worked example: how the pieces fit

Following add buy milk through the program:

Step What happens
1 main reads the line add buy milk with input
2 run_command splits it: command add, argument buy milk
3 todo.add("buy milk") strips and checks the title, creates Task(1, "buy milk"), appends it
4 todo.save() converts the tasks with asdict, writes JSON to todo.tmp, then replaces todo.json
5 run_command returns "added 1: buy milk" and main prints it

What each part knows:

Part Knows about
Task its own three fields
TodoList lists of tasks and the file; nothing about commands or the screen
run_command command words and messages; nothing about files
main the keyboard and screen

Because of that split, replacing the interface (a window, a web page) or the storage (a database) changes one layer and leaves the others and the tests alone. This is the main lesson of the project.

Common mistakes

  • Saving only at the end of the program, so a crash loses everything (this program saves after every change).
  • Writing the file directly, risking a half-written file.
  • Putting print and input in the class, which makes it hard to test or reuse.
  • Using the list position as the task id, so ids change when tasks are removed.
  • Not handling a missing or damaged file.
  • Forgetting encoding="utf-8".
  • Using a mutable default or shared list between lists (each TodoList builds its own).

Key takeaways

  • To remember data between runs, store it in a file: JSON is a good simple format.
  • Dataclasses plus asdict and Task(**item) convert records to and from JSON.
  • Save after each change, through a temporary file and replace, and handle missing and damaged files with clear errors.
  • Keep storage logic, command handling and the interface in separate layers; return text rather than printing.
  • Test with temporary files, and test the error paths.

Practice

1. What does max((t.id for t in self.tasks), default=0) + 1 return for an empty list?

Show answer

1: max of nothing returns the default 0, plus 1.

2. Why does TodoList return [] when the file is missing?

Show answer

On the first run there is no file yet, which is normal; an empty list is the correct starting state.

3. How would you add an undone <id> command?

Show answer

Add a reopen(task_id) method that sets done = False and saves, plus an undone branch in run_command that calls it with parse_id(argument).

4. Why does run_command return text instead of printing it?

Show answer

Tests can check the returned text directly, and the same function can be reused by a different interface.

5. What could go wrong if save wrote straight to todo.json?

Show answer

A crash during the write could leave a partly written, invalid file, losing the old list too. A temporary file plus replace avoids that.

6. How would you store the tasks in SQLite instead, keeping the tests valid?

Show answer

Re-implement _load and save (or the methods) to use a table, keeping the public methods and their behaviour the same, so the tests of add, complete, remove and the commands still pass.